有的時候我們需要做一個當滑鼠放置在圖檔上的時候,希望圖檔逐漸變大,即圖檔的width和height逐漸變大,但是此時,其left值與top值沒有改變,故看似不是從中心點進行縮放的。如下圖:
從中心點進行縮放
實作代碼如下:
<meta charset="utf-8">
<style type="text/css">
#div1{ width:600px; height:400px; margin:50px auto; position:relative; text-align: center; padding-left:50px;}
#div1 img{ position:absolute; left:0; top:0; margin: 0 auto;}
</style>
<div id="div1">
<img src="images/1.jpg" width="100px" height="80px">
</div>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function(){
$('#div1 img').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 補充
今天發現,上面的動畫,其實還是有一個小問題的。就是當我多次在相應的元素上移入和移除的時候,就會執行多次mouseenter、mouseleave,當然有人會想,這樣會有什麼問題呢?那麼就看下圖
也就是當我的滑鼠移出來了,還在反複執行mouseenter、mouseleave。為什麼會這樣呢?因為JS事件隊列中有多個等待執行的動畫,關于事件隊列,我覺得回頭有必要好好總結一下。
修改方案
Jquery提供了stop方法,停止所有在指定元素上正在運作的動畫,如下圖
修改後效果下圖
最終JS部分代碼如下
<script type="text/javascript">
$(function(){
$('#div1 img').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.findme.wang
$(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 );
});
});