2011-09-09 34 views
1

我想保留originalWidth和originalHeight属性中每个IMG宽度和高度的副本。如何稍后使用它们将每个IMG的新大小设置为originalWidth * k,originalHeight * k?我想我应该使用lambdas或类似的东西,但没有想法如何编写表达式,因为我是JS的新手。jQuery:每个IMG的大小相乘

$("//img[@attrName='value']").style = ???? ; 

回答

1

我会做这样的事情(工作jsFiddle example here):

// To store the height and width of each image as data: 
$('img').each(function() { 
    $elem = $(this); 
    $elem.data({ 
     'origHeight': $elem.height(), 
     'origWidth': $elem.width() 
    }); 
}); 

// To set the size of each image based on a multiplier "new_size": 
function resize_images(new_size) { 
    $('img').each(function() { 
     $elem = $(this); 
     $elem.height($elem.data('origHeight') * new_size); 
     $elem.width ($elem.data('origWidth') * new_size); 
    }); 
} 
2

您将需要使用.each()并为每个图像做分开。

$("img[attrName='value']").each(function() { ... do stuff .... }); 
+0

谢谢你,佩卡。但是,“做什么”可以看起来像什么? a => a.Width * = k? – noober

+1

@noober你可以使用'$(this).width()'来访问函数中每个图像的宽度(高度也一样) –

3

你可以使用data()方法

$("img").each(function() { 
    $(this).data({ 
     "width": $(this).width(), 
     "height": $(this).height() 
    }); 
}); 
1
var multiply_by = 2; // example 

$("img[attrName='value']").each(function() { 

    // set multiplied width and height 
    $(this).width($(this).width() * multiply_by) 
      .height($(this).height() * multiply_by); 

}); 
2

你有没有考虑过使用$.data存储它们?或者,如果您真的需要自定义,甚至可以读取HTML5 data-*自定义属性。

然后你就可以在Java中,LILE写一些UTIL FUNC:

function imgResize($img, k){ 
    var w = $img.data('originalWidth'), 
     h = $img.data('originalHeight'); 
    $img.width(w*k).height(h*k); 
} 
1

如果你想要做的是获取您的自定义属性,并用它们来设置一个新的大小为您的图片,然后通过:

var k = 2; //double the size of the image 
var origW = parseInt($("img").attr("originalWidth")); 
var origH = parseInt($("img").attr("originalHeight")); 

$("img").css("width", origW*k); 
$("img").css("height", origH*k); 
// or 
$("img").attr("width",origW*k); 
$("img").attr("height",origH*k);