事件对象+放大镜案例

一、事件对象:
  1. 只要触发了某一个事件,就会产生一个相应的事件对象,这个event对象中包含着与这一事件相关的信息,所以通过事件对象就可获取任意相关事件的属性。
  2. 考虑到兼容问题,通常这样写(以onclick事件为例):
event.onclick=function(event){//当点击事件产生时,event就会被接受
	var event=event || window.event;//解决兼容问题
}
  1. 常见属性:
属性用途
clientX光标相对于网页的水平位置
clientY光标相对于网页的垂直位置
pageX光标相对于网页的水平位置
pageY光标相对于网页的垂直位置
screenX光标相对于屏幕的水平位置
screenY光标相对于屏幕的垂直位置
type该事件的类型
target该事件被传送到的对象
width该窗口或框架的宽度
height该窗口或框架的高度

注意:

  • pageX、pageY是以当前文档为基准(若有滚动条,则会将滚动的区域算进去)。
  • clientX、clientY是以当前可视区域为基准,无关乎滚动的区域。
  1. JS常见事件
事件触发
onclick鼠标点击当前元素时就会触发
onmouseover鼠标进入当前元素时就会触发
onmouseout鼠标离开当前元素时就会触发
onmousemove鼠标在当前元素中移动时就会触发
onmouseup当鼠标弹起来是就会触发
onmousedown当鼠标按下时就会触发
  • onmouseup和onmousedown组合就成了onclick事件
二、放大镜
<script type="text/javascript">
		window.onload=function(){
			//1.获取需要的标签
			var box=document.getElementById("box");
			var small_box=box.children[0];
			var big_box=box.children[1];
			var mask=small_box.children[1];
			var big_pic=big_box.children[0];

			//2.监听鼠标进入small_box
			small_box.onmouseover=function(){
				//2.1将隐藏的mask和big_pic显示出来
				mask.style.display='block';
				big_box.style.display='block';
				//2.2监听鼠标的移动
				small_box.onmousemove=function(event){
					var event=event || window.event;//解决兼容问题
					//2.3求鼠标的位置
					var X=event.clientX-small_box.offsetParent.offsetLeft - 0.5* mask.offsetWidth;
					var Y=event.clientY-small_box.offsetParent.offsetTop - 0.5* mask.offsetHeight;
					//2.4边界的处理
					if(X<0){
						X=0;
					}else if(X>small_box.offsetWidth-mask.offsetWidth){
						X=small_box.offsetWidth-mask.offsetWidth;
					}
					if(Y<0){
						Y=0;
					}else if(Y>small_box.offsetHeight-mask.offsetHeight){
						Y=small_box.offsetHeight-mask.offsetHeight;
					}
					//2.5使mask移动起来
					mask.style.left=X+'px';
					mask.style.top=Y+'px';
					//2.6让big_pic按照比例移动移动起来
					big_pic.style.left=-X/(small_box.offsetWidth/big_box.offsetWidth)+'px';
					big_pic.style.top=-Y/(small_box.offsetHeight/big_box.offsetHeight)+'px';

				}
				//3.鼠标离开small_box
				small_box.onmouseout=function(){
					mask.style.display='none';
					big_box.style.display='none';
				}
	
			}
		}
	</script>

效果图:

注意事项:

  1. offsetWidth、clientWidth返回的是数字,而style.width返回的是字符串,故此,一定要加上+'px'!

mask.style.left=X+'px';

  1. 放大的是按照small_pic和big_pic的比例来放大的,即:

smallX/bigX=small_pic.width/big_pic.width;
smallY/bigY=small_pic.height/big_pic.height;

  1. 一定要先进行边界处理后再写onmouseout事件,程序运行是有先后行的!
  2. 鼠标向右移动,实际上是big_pic向左移动放大,要加上负号。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值