Using jQuery to capture image height

I have a bunch of images on the page. I am trying to use jQuery to capture the height of each image and display it after the image. So here is my code:



$(document).ready(function() {
  $(".thumb").each(function() {
    imageWidth = $(".thumb img").attr("width");
    $(this).after(imageWidth);
  });
});

<div class="thumb"><img src="" border="0" class="thumb_img"></div>
<div class="thumb"><img src="" border="0" class="thumb_img"></div>
<div class="thumb"><img src="" border="0" class="thumb_img"></div>

[...]

code>

My jQuery logic is that I want to go through each "thumb" selector, assign the height img inside the "thumb" to the variable "imageWidth", and then display the height in the text after each thumb.

The problem I am facing is that it only works with the first image and then leaves. I can make it work if I use the thumb_img class, of course, but I need access to the image height for the thumb class.

, , jQuery. .

+3
4

:

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

:

$(".thumb img")

... , ,

... jquery, :

var $this = $(this)

$, . , .

+9

document.ready(), , .

onload(), , .

, , .

+10
$().ready(function() {

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

        });

});
0
source

I used something similar to preloading the image and installed some code in mouseover and mouseout and set the style for all images with class name "swap". It did $(this)n’t work for me , but it thisworked directly :

// 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";
    });
}
0
source

Source: https://habr.com/ru/post/1715107/


All Articles