0

I am using bootstrap row-fluid with images in it. Dimensions of this images changes when the browser window changes so is there any event listener that triggers when image resize happens? I want it to use to get image width. I have tried this:

$(window).load(function() {
    $('img.product-thumbnail').resize(function(){
        alert($('img.product-thumbnail').width());
    });
});

and my img tags are:

<img src="img/produkt1.png" title="Názov produktu" class="product-thumbnail">
<img src="img/produkt2.png" title="Názov produktu" class="product-thumbnail">

5 images total. Right now I am not getting any alerts but I know that img changed its size (chrome dev tools > show dimensions). Is there any way to acomplish this? (jquery is included so there shouldnt be problem with selectors)

4

1 回答 1

0

没有任何真正简单的方法可以做到这一点。jQuery resize() 事件旨在捕获窗口调整大小事件,而不是监听单个元素。

考虑到这一点,为了便于解释,请允许我提出以下建议:

1)在窗口加载时,抓取图像尺寸并将它们粘贴到一个data-属性中:

$(window).load(function() {
    $('img.product-thumbnail').each(function(){
    var $this = $(this),
        // get the image dimensions 
        thisWidth = $this.width(),
        thisHeight = $this.height();

        // push them into an attribute 
        $(this).attr('data-width', thisWidth);
        $(this).attr('data-height', thisHeight);
    });
});

2)将事件绑定到窗口调整大小并检查:

$(window).resize(function(){
    // loop over each, checking dimensions
    $('img.product-thumbnail').each(function(){
        var $this = $(this),
            // get the image dimensions 
            thisWidth = $this.width(),
            thisHeight = $this.height();

       //check that there are data-attribtues before going further
       if($this.attr('data-height').length){
           if(thisWidth !== $this.attr('data-width')){
               //width has changed
           }
           if(thisHeight !== $this.attr('data-height')){
               //height has changed
           }
       }
    }
});

这是一个非常快速、未经测试且未经优化的代码,但其背后的理论是可靠的,应该有助于为您提供一个很好的起点来检测图像是否改变了大小。

于 2013-06-10T16:43:18.310 回答