JQuery控制圖片由中心點逐漸放大效果

黄舟
發布: 2017-03-01 14:44:07
原創
1576 人瀏覽過

有的時候我們需要做一個當滑鼠放置在圖片上的時候,希望圖片逐漸變大,即圖片的width和height逐漸變大,但是此時,其left值與top值沒有改變,故看似不是從中心點進行縮放的。如下圖:


從中心點進行縮放

實作程式碼如下:


<meta charset="utf-8">
<style type="text/css">
#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 id="p1">
	<img src="images/1.jpg" width="100px" height="80px">
</p>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
	$(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 補充**************** ***************************************************/

2016年6月26 補充

今天發現,上面的動畫,其實還是有個小問題的。就是當我多次在對應的元素上移入和移除的時候,就會執行多次mouseenter、mouseleave,當然有人會想,這樣會有什麼問題呢?那就看下圖



#也就是當我的滑鼠移出來了,還在重複執行mouseenter、mouseleave。為什麼會這樣呢?因為JS事件隊列中有多個等待執行的動畫,關於事件隊列,我覺得回頭有必要好好總結一下。


修改方案

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


修改後效果下圖


#最終JS部分程式碼如下


<script type="text/javascript">
	$(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 補充


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

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

$(function(){
	$(&#39;.focus_news&#39;).mouseenter(function(){
		var imgObj=$(this).find(&#39;img&#39;);	
		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(&#39;.com_news_title&#39;).css(&#39;color&#39;,&#39;#F59300&#39;);
	}).mouseleave(function(){
		$(this).find(&#39;.com_news_title&#39;).css(&#39;color&#39;,&#39;#52A2DE&#39;);
		$(this).find(&#39;img&#39;).stop().animate({width: "100%",
									 height: "100%",
									 left:"0px",
									 top:"0px"}, 500 );
	});
});
登入後複製

 以上就是JQuery控制圖片由中心點逐漸放大效果的內容,更多相關內容請關注PHP中文網(www.php.cn)!


#
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!