Dan*_*cer 4 jquery this jquery-animate
晚上所有 - 什么是动态访问图像高度和宽度的最佳方式.
我想在图像的宽度和高度上添加20%,并在周围的div悬停时动画,我想我需要使用'this',但不知道如何访问图像.
任何帮助都很受欢迎.
干杯保罗
您可以使用.height()和.width()使用函数参数执行类似的操作:
$("img").hover(function() {
$(this).height(function(i, h) { return h * 1.2; })
.width(function(i, w) { return w * 1.2; });
}, function() {
$(this).height(function(i, h) { return h / 1.2; })
.width(function(i, w) { return w / 1.2; });
});?
Run Code Online (Sandbox Code Playgroud)
你可以在这里尝试一下,如果你想要一个平滑的动画,你可以存储初始的高度/宽度.animate(),如下所示:
$("img").each(function() {
$.data(this, 'size', { width: $(this).width(), height: $(this).height() });
}).hover(function() {
$(this).stop().animate({ height: $.data(this,'size').height*1.2,
width: $.data(this,'size').width*1.2 });
}, function() {
$(this).stop().animate({ height: $.data(this,'size').height,
width: $.data(this,'size').width });
});?
Run Code Online (Sandbox Code Playgroud)
您可以在这里尝试一下,确保运行其中任何一个选项$(window).load(),而不是 $(document).ready(),因为可能尚未加载维度.
$(".divs").mouseover(function() {
var $div = $(this);
var $item = $div.find("img");
var width = $item.width();
var height = $item.height();
width = width * 1.2;
height = height * 1.2;
$item.width(width);
$item.height(width);
});
Run Code Online (Sandbox Code Playgroud)