jQuery抓取高度和运行函数仅用于此项

jQuery grab height and run function only for this item

本文关键字:用于 函数 运行 抓取 取高度 jQuery      更新时间:2023-09-26

我有一个图像库,每个图像都有不同的大小,我想在悬停的图像上垂直居中放置一个图标。我一直在尝试用下面的代码来解决这个问题,我成功地获取了图像的所有高度,但我不知道如何将图像悬停的一个特定高度应用到等式中并运行函数。以下是我的代码:

$(document).ready(function() {
var wrapper = $('.img-wrap', this); // Grab the wrapper, same as image size
    wrapper.prepend("<div class='cover'><img src='imgs/icons/search.png' alt='zoom into photo'></div>") // this is not so important
wrapper.each(function() {
    $this = $(this);
    var $height = $this.height(); // Get height of Wrapper or Image (same size)
    var $marginHeight = ($height - 32) / 2; // Height of Wrapper - Icon Size (32px) and divided by two to only get one half
    console.log($height) // Check height
    console.log($marginHeight) // Check one half 

    // Main problem
    wrapper.hover(
        function() {
            $('.cover img', this).css({
                "marginTop": $marginHeight
            });
        });

    // this runs fine
    wrapper.mouseout(
        function() {
            $('.cover img', this).css({
                "marginTop": 0
            });
        });
    });
});
$(document).ready(function() {
    $('.img-wrap')
        .prepend("<div class='cover'><img src='imgs/icons/search.png' class="cover_img" alt='zoom into photo'></div>")
        .on('mouseenter mouseleave', function(e) {
            var h = e.type == 'mouseenter' ? ($(this).height() - 32) / 2 : 0;
            $(this).find('.cover_img').css('margin-top', h);
    });
});

FIDDLE