开发者

How to hack an image height standard with jQuery?

开发者 https://www.devze.com 2023-01-22 03:48 出处:网络
I need a jQuery function to measure the height of an image, and add margin to the IMG element, so it will always result with a regular number that divides by 17 (which is my line-height).

I need a jQuery function to measure the height of an image, and add margin to the IMG element, so it will always result with a regular number that divides by 17 (which is my line-height).

Any help would be appreciated. Thanks.

UPDATE: I changed the title of the question and replaced PHP with jQuer开发者_开发知识库y. Coming to think about it, I need the function to run after the DOM is ready, on all images in a specific DIV. jQuery is more sensible than PHP in that case.


If I understand your question correctly you want to know how to get each image height and add a margin as needed to get the height to a number evenly divisible by 17.

Here is a quick stab at the issue:

$(document).ready(function(){
       $('img').each(function() {
             var height = $(this).height;
             var modulus = height % 17;
             if(modulus != 0) {
                 var marginToAdd = 17 - modulus;
                 $(this).css("margin-bottom", marginToAdd); 
             }
       });
});

So what the above does is get each image on the page by it's tag. If you don't want every image on the page you might want to put all the images in a container so you have a more discriminating selector. Then it get the remainder from the division of the height by 17. If the remainder is 0 it does nothing if it is non-zero it figures out the margin that needs to be added to make it evenly divisible by 17 and adds it to the bottom of the image.


$(this).children("img").attr("height")

There is a very similar question here: Using jQuery each to grab image height


jQuery has some problems with document ready and image load on this issue.

if you want to check the image sizes you need to know if the image has been loaded or not because you can have the dom ready without the images loaded or the image will not trigger the onload event

so:

var image = $('#image');
if(image.get(0).complete){
    do_what_you_need();
} else {
    image.load(function(e){
        do_what_you_need();             
    });
}


You can use GD library: http://php.net/manual/en/function.getimagesize.php


You can get image height with jquery simply by doing

 $('#my_img_id').height();

For DOM ready, just check http://api.jquery.com/ready/

Edit: Is that what you were looking for?

<script>
$(function(){
    $('#myDiv img').each(function(){
        alert($(this).height()); 
    });
});

</script>
<div id="myDiv">
    <img src="asd.png">
    <img src="gg.png">
</div>
0

精彩评论

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