Using jQuery each to grab image height

蓝咒 提交于 2019-12-06 05:18:53

Use this:

imageWidth = $(this).children("img").attr("width")

The following selects all your images:

$(".thumb img")

... so when you ask for the attribute it returns it from the first object in the collection

Sorry for all the edits... but it is best to reuse jquery objects, so:

var $this = $(this)

Then refer to $this were needed for optimization. Not that big a deal in this example, but it is a good practice to use.

You won't be able to use document.ready() to do this as the images will not have loaded by the time that is called.

You actually need to put this code into the onload() event handler, which is called after the document and all images have finished loading.

It is only when the images have finished loading that the browser knows how big they are.

$().ready(function() {

        $(".thumb img").load(function() {
            var imageHeight = $(this).height();
            $(this).parent().append(imageHeight);

        });

});

I have used something similar to preload an image and set some code in mouseover and mouseout and set the style for all images with a class name "swap". For me $(this) did not work but directly this worked:

// in jquery
$(document).ready(function(){
        swapAndPreload();
    });

function swapAndPreload(){
    $(".swap").each(function(){
        // preload images in cache
        var img = new Image();
        img.src=this.src.replace(/([-_])out/,'$1over');
        //set the hover behaviour
        this.onmouseover = function(){
            this.src=this.src.replace(/([-_])out/,'$1over');
        }
        //set the out behaviour
        this.onmouseout = function(){
            this.src=this.src.replace(/([-_])over/,'$1out');
        }
        //set the cursor style
        this.style.cursor="pointer";
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!