Jquery – hover时将图像高度和宽度扩展20%
晚上所有 – 什么是动态访问图像高度和宽度的最佳方式。
我想在周围的divhover时添加20%的图像宽度和高度以及动画,我想我需要使用’this’,但不知道如何访问图像。
任何帮助都很受欢迎。
干杯保罗
您可以使用带有函数参数的.height()
和.width()
来执行.height()
:
$("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; }); });
你可以在这里尝试一下 ,如果你想要一个平滑的动画你可以存储初始高度/宽度和.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 }); });
你可以在这里尝试一下 ,确保在$(window).load()
运行这些选项中的任何一个,而不是 $(document).ready()
,因为维度可能尚未加载。
使用jQuery的width
和height
方法:
$(".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); });
$("#divId").mouseover(function() { var o = $("#imgid"); o.width(o.width()*1.2).height(o.height()*1.2); });
这是一种使用animate的方法,它应该提供更平滑的过渡:
$("img").hover(function() { var $this = $(this); $this.animate({ 'height': $this.height() * 1.2, 'width' : $this.width() * 1.2 }); },function() { var $this = $(this); $this.animate({ 'height': $this.height() / 1.2, 'width' : $this.width() / 1.2 }); });