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学习者快速成长!