我有一个图片库,每个图片都有不同的尺寸,我想在悬停的图片上垂直居中一个图标。我一直在尝试用下面的代码解决这个问题,我成功地抓住了图像的所有高度,但我不知道如何只将一个特定的高度(图像悬停)应用到方程中并运行函数. 以下是我的代码:
$(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
});
});
});
});