4-21

js的事件对象--event

1.只要出发Dom上的某一个事件时,会产生一个事件对象event,这个对象包含着所有与事件有关的信息。

兼容性写法:var event =event || window.event;

2.常用属性

clientX,clientY:光标对于该网页的水平、垂直位置;

type:事件的类型;

traget:该事件被传送到的对象;

screenX,screenY:光标相对于该屏幕的水平、垂直位置;

pageX,pageY:光标相对于该网页的水平、垂直位置;

width,height:该窗口的宽度、高度

3.常见事件

onmousemove:鼠标在当前元素中移动

onmouseover:鼠标进入当前元素

onmouseup:鼠标弹起

onmousedown:鼠标按下

 

用今天学的event和昨天学的offset做了个简单的放大器,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大镜</title>
<style>
* {
margin: 0;
padding: 0;
border: none;
}

#sBox {
width: 400px;
height: 400px;
position: relative;
margin: 100px 0 0 100px;
}

#sBox img {
width: 400px;
height: 400px;
}

#sBox #mask {
width: 70px;
height: 70px;
background-color: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0;
left: 0;

cursor: move;
display: none;
}

#lBox {
width: 500px;
height: 500px;
/*display: none;*/
overflow: hidden;
border: 1px solid #cccccc;
position: absolute;
top: 100px;
left: 700px;
}

#lBox img {
position: absolute;
top: 0;
left: 0;
width: 900px;
height: 900px;
}
</style>
</head>
<body>
<div id="sBox">
<img src="images/lingkpark.png" alt="">
<span id="mask"></span>
</div>
<div id="lBox">
<img src="images/lingkpark.png" alt="">
</div>

<script>
window.onload = function () {
var sBox = document.getElementById("sBox");
var lBox = document.getElementById("lBox");
var mask = sBox.children[1];
var lImg = lBox.children[0];

//2.监听鼠标进入盒子
sBox.onmouseover = function () {
//2.1把隐藏的内容显示
mask.style.display = 'block';
lBox.style.display = 'block';

//2.2监听鼠标移动
sBox.onmousemove=function (event) {
var event=event || window.event;

//2.3求出鼠标的坐标
var pointX=event.clientX-sBox.offsetLeft-mask.offsetWidth/2;
var pointY=event.clientY-sBox.offsetTop-mask.offsetHeight/2;

//2.4设置边界
if(pointX<0){
pointX=0;
}else if(pointX>=sBox.offsetWidth-mask.offsetWidth){
pointX=sBox.offsetWidth-mask.offsetWidth
}
if(pointY<0){
pointY=0;
}else if(pointY>=sBox.offsetHeight-mask.offsetHeight){
pointY=sBox.offsetHeight-mask.offsetHeight
}

//2.5放大镜移动
mask.style.left=pointX+'px';
mask.style.top=pointY+'px';

//2.6大图(换算)
lImg.style.left=-pointX/(4/5)+'px';
lImg.style.top=-pointY/(4/5)+'px';
}
};

//3.监听鼠标离开盒子
sBox.onmouseout = function () {
//3.1隐藏内容
mask.style.display = 'none';
lBox.style.display = 'none';
}

}
</script>
</body>
</html>
posted @ 2019-04-21 21:46  不要呀  阅读(157)  评论(0)    收藏  举报