开发者

jQuery: multiply size of every IMG

开发者 https://www.devze.com 2023-04-03 22:20 出处:网络
I want to keep copies of every IMG width and height in originalWidth and originalHeight att开发者_运维问答ributes. How can I use them later to set new size of every IMG as originalWidth * k, originalH

I want to keep copies of every IMG width and height in originalWidth and originalHeight att开发者_运维问答ributes. How can I use them later to set new size of every IMG as originalWidth * k, originalHeight * k? I think I should use lambdas or something like them, but have no ideas how to write the expression since I'm newbie at JS.

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


You could store them using the data() method

$("img").each(function() {
    $(this).data({
        "width": $(this).width(),
        "height": $(this).height()
    });
});


You will need to use .each() and do it separately for each image.

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


Did you considered using $.data? Or, if you realy need custom it even reads HTML5 data-* custom attributes.

Then you can write some util func in java, lile:

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


I would do something like this (working 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);
    });
}


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);

});


If all you want to do is fetch your custom attributes and use them to set a new size for your image then:

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消