JQuery控制圖片由中心點(diǎn)逐漸放大效果

有的時(shí)候我們需要做一個(gè)當(dāng)鼠標(biāo)放置在圖片上的時(shí)候,希望圖片逐漸變大,即圖片的width和height逐漸變大,但是此時(shí),其left值與top值沒有改變,故看似不是從中心點(diǎn)進(jìn)行縮放的。如下圖:

JQuery控制圖片由中心點(diǎn)逐漸放大效果

從中心點(diǎn)進(jìn)行縮放

JQuery控制圖片由中心點(diǎn)逐漸放大效果

實(shí)現(xiàn)代碼如下:

<meta><style>  #p1{ width:600px; height:400px; margin:50px auto; position:relative;  text-align: center; padding-left:50px;}  #p1 img{ position:absolute; left:0; top:0; margin: 0 auto;}  </style><p>  	@@##@@  </p>  <script></script><script>  	$(function(){  		$(&#39;#p1 img&#39;).mouseenter(function(){  			var wValue=1.5 * $(this).width();  			var hValue=1.5 * $(this).height();		  			$(this).animate({width: wValue,  							height: hValue,  							left:("-"+(0.5 * $(this).width())/2),  							top:("-"+(0.5 * $(this).height())/2)}, 1000);  		}).mouseleave(function(){  			$(this).animate({width: "100",  										 height: "80",  										 left:"0px",  										 top:"0px"}, 1000 );  		});  	});  </script>

/******************************2016年6月26 補(bǔ)充*******************************************************************/

2016年6月26 補(bǔ)充

今天發(fā)現(xiàn),上面的動畫,其實(shí)還是有一個(gè)小問題的。就是當(dāng)我多次在相應(yīng)的元素上移入和移除的時(shí)候,就會執(zhí)行多次mouseenter、mouseleave,當(dāng)然有人會想,這樣會有什么問題呢?那么就看下圖

JQuery控制圖片由中心點(diǎn)逐漸放大效果

也就是當(dāng)我的鼠標(biāo)移出來了,還在反復(fù)執(zhí)行mouseenter、mouseleave。為什么會這樣呢?因?yàn)镴S事件隊(duì)列中有多個(gè)等待執(zhí)行的動畫,關(guān)于事件隊(duì)列,我覺得回頭有必要好好總結(jié)一下。

修改方案

Jquery提供了stop方法,停止所有在指定元素上正在運(yùn)行的動畫,如下圖

JQuery控制圖片由中心點(diǎn)逐漸放大效果

修改后效果下圖

JQuery控制圖片由中心點(diǎn)逐漸放大效果

最終JS部分代碼如下

<script>  	$(function(){  		$(&#39;#p1 img&#39;).mouseenter(function(){  			var wValue=1.5 * $(this).width();  			var hValue=1.5 * $(this).height();		  			$(this).stop().animate({width: wValue,  							height: hValue,  							left:("-"+(0.5 * $(this).width())/2),  							top:("-"+(0.5 * $(this).height())/2)}, 1000);  		}).mouseleave(function(){  			$(this).stop().animate({width: "100",  										 height: "80",  										 left:"0px",  										 top:"0px"}, 1000 );  		});  	});  </script>

2017年02月28 補(bǔ)充

解決:如果快速移出,移入停留,圖片可以無限放大

最終代碼如下,效果圖見?http://www.php.cn/

$(function(){  	$('.focus_news').mouseenter(function(){  		var?imgObj=$(this).find('img');	  		imgObj.stop().css({width:?"100%",height:?"100%",left:"0px",top:"0px"});	  		var?wValue=1.5?*?imgObj.width();  		var?hValue=1.5?*?imgObj.height();  		imgObj.animate({  			width:?wValue,  			height:?hValue,  			left:("-"+(0.5?*?imgObj.width())/2),  			top:("-"+(0.5?*?imgObj.height())/2)},?500);  		$(this).find('.com_news_title').css('color','#F59300');  	}).mouseleave(function(){  		$(this).find('.com_news_title').css('color','#52A2DE');  		$(this).find('img').stop().animate({width:?"100%",  									?height:?"100%",  									?left:"0px",  									?top:"0px"},?500?);  	});  });

?以上就是JQuery控制圖片由中心點(diǎn)逐漸放大效果的內(nèi)容,更多相關(guān)內(nèi)容請關(guān)注PHP中文網(wǎng)(www.php.cn)!

JQuery控制圖片由中心點(diǎn)逐漸放大效果

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊9 分享