<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>点击方块 移动</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.div{
width: 400px;
height:400px;
margin: 100px;
border: 1px solid #333;
position: relative;
left: 0px;
}
.mask{
width: 200px;
height: 200px;
border:1px solid yellow;
background-color: yellow;
position: absolute;
top: 0;
opacity: 0.5;
display: none;
cursor: move;
}
.big{
width: 400px;
height:400px;
border: 1px solid #333;
position: absolute;
top: 0px;
left: 500px;
display: none;
overflow: hidden;
}
img{
width: 100%;
}
</style>
</head>
<body>
<div id="">
<div class="div">
<img src="https://img14.360buyimg.com/n1/s450x450_jfs/t1/132382/31/23673/311148/6220170fEd0692b77/a49312c8dbbc0445.jpg" >
<div class="mask">
</div>
</div>
<div class="big">
<img src="https://img14.360buyimg.com/n1/s450x450_jfs/t1/132382/31/23673/311148/6220170fEd0692b77/a49312c8dbbc0445.jpg" style="width: 600px; position: absolute;" >
</div>
</div>
<script type="text/javascript">
var mask = document.querySelector('.mask')
var div = document.querySelector('.div')
var big = document.querySelector('.big')
var img = big.children[0]
div.addEventListener('mouseover',function(){
mask.style.display ='block'
big.style.display = 'block'
div.addEventListener('mousemove',function(e){
// 鼠标的坐标
var x =e.pageX - div.offsetLeft
var y =e.pageY - div.offsetTop
// 鼠标移动的距离 //遮挡层的移动距离
var mouseMoveX = x- mask.offsetWidth/2
var mouseMoveY = y- mask.offsetHeight/2
// 盒子可以移动的距离 //遮挡层的移动最大距离
var divMaxX = div.offsetWidth - mask.offsetWidth
var divMaxY = div.offsetHeight - mask.offsetHeight
// 大图片最大的移动距离
var imgMax = img.offsetWidth - div.offsetWidth
console.log(imgMax)
if(mouseMoveX <= 0 ){
mouseMoveX =0
}else if(mouseMoveX > divMaxX){
mouseMoveX = divMaxX
}
if(mouseMoveY <= 0 ){
mouseMoveY =0
}else if(mouseMoveY > divMaxY){
mouseMoveY = divMaxY
}
mask.style.left = mouseMoveX + 'px'
mask.style.top = mouseMoveY + 'px'
// 有个公式 移动的倍数 = 遮挡层的移动距离 * 大图片最大的移动距离 / 遮挡层的移动最大距离
var flagX = mouseMoveX * imgMax / divMaxX
var flagY = mouseMoveY * imgMax / divMaxY
// var flag = img.offsetWidth/ mask.offsetWidth
// console.log(flag)
img.style.left = "-"+ flagX +'px'
img.style.top = "-"+ flagY +'px'
})
})
div.addEventListener('mouseout',function(){
mask.style.display = 'none'
big.style.display = 'none'
})
</script>
</body>
</html>
相关推荐
© 2020 asciim码
人生就是一场修行