主要是练习一下事件以及DOM的高度之类的
鼠标事件以及clientX、offsetX、screenX、pageX、x的区别
- clientX代表点击位置距离当前body可视区域的宽度
- offsetX相对于带有定位的父盒子的x和y坐标
- screeX,代表当前点击位置距离当前电脑屏幕的x、y坐标,电脑屏幕的左上角为(0,0)
- pageX,当前点击位置距离整个文档的左上角的位置。
放大镜
<div class="box">
<div class="drag"></div>
</div>
<div class="big"></div>
布局部分
<style>
*{
padding:0;
margin:0;
}
.box{
position: relative;
width: 400px;
height: 240px;
background: url('1.jpg');
background-size: 400px 240px;
}
.drag{
width: 100px;
height: 80px;
background: #000000;
opacity: 0.5;
border: 1px solid #fff;
position: absolute;
left: 0;
right: 0;
}
.big{
position: fixed;
left: 600px;
top: 100px;
width: 300px;
height: 240px;
overflow: hidden;
border:1px solid #000;
background:url(1.jpg);
background-size: 1200px 720px;
/* background-position: 30px 20px; */
background-repeat: no-repeat;
background-position:scale(3)
}
</style>
逻辑实现
<script>
var drag=document.querySelector('.drag');
var box=document.querySelector('.box')
var big=document.querySelector('.big')
box.onmousedown=function(e){
let ofx = e.offsetX;//相对于父元素的坐标
let ofy = e.offsetY;
// console.log("可视区域",ofx,ofy);
box.onmousemove=(e)=>{
let clx=event.clientX;//相对于可视区域的坐标
let cly=event.clientY;
// console.log("鼠标",clx,cly);
let x=clx-ofx;//盒子的左定位
let y=cly-ofy;
if(x>=300){//限制一下
x=300
}else if(x<=0){
x=0
}
if(y>=160){
y=160
}else if (y<=0){
y=0
}
drag.style.left=x+'px';
drag.style.top=y+'px';
big.style.backgroundPositionX=-3*x+'px';//因为大图是其三倍,小盒子走一点点,大图就要挪动三倍
big.style.backgroundPositionY=-3*y+'px';
}
}
box.onmouseup=function(){
box.onmousemove=null;//抬起要去掉移动的事件
}
</script>