<!DOCTYPE html>
<html lang="en">
<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>
* {
padding: 0;
margin: 0;
list-style: none;
}
img{
vertical-align: top;
}
#box {
margin: 100px 0 0 100px;
width: 350px;
height: 350px;
position: relative;
}
#midbox {
width: 100%;
height: 100%;
border: 1px solid #ccc;
position: relative;
}
#midbox img {
width: 350px;
height: 350px;
}
#box ul li {
float: left;
width: 50px;
height: 50px;
margin: 3px;
cursor: pointer;
}
#box ul li img {
width: 100%;
height: 100%;
}
#bigbox {
width: 600px;
height: 600px;
position: absolute;
left: 360px;
top: 0px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
#mask {
width: 100px;
height: 100px;
background-color: rgba(255,255,0,0.4);
display: none;
position: absolute;
left: 0;
right: 0;
cursor: move;
}
</style>
</head>
<body>
<div id="box">
<div id="midbox">
<span id="mask"></span>
<img src="images/pic001.jpg" alt="">
</div>
<ul>
<li><img src="images/pic0001.jpg" alt=""></li>
<li><img src="images/pic0002.jpg" alt=""></li>
<li><img src="images/pic0003.jpg" alt=""></li>
</ul>
<div id="bigbox">
<img src="images/pic01.jpg" style="position: absolute; left:0; top:0;">
</div>
</div>
</body>
<script>
window.addEventListener('load',function(){
let box = document.getElementById('box')
let liList = box.children[1].getElementsByTagName('li')
let midbox = box.children[0]
let mask = midbox.children[0]
let midboxImg = midbox.children[1]
let bigbox = document.getElementById('bigbox')
let bigboxImg = bigbox.children[0]
midbox.addEventListener('mousemove',function(event){
let e = event || window.event
mask.style.display = 'block'
bigbox.style.display = 'block'
console.log(e.pageX,e.pageY)
let X = e.pageX - box.offsetLeft - mask.offsetWidth*0.5;
let Y = e.pageY - box.offsetTop - mask.offsetHeight*0.5;
console.log(X,Y)
console.log(mask.offsetWidth,mask.offsetHeight)
if (X<0) {
X = 0
}else if (X>midbox.offsetWidth-mask.offsetWidth) {
X= midbox.offsetWidth-mask.offsetWidth
}
if (Y<0) {
Y = 0
}else if (Y>midbox.offsetHeight-mask.offsetHeight) {
Y = midbox.offsetHeight-mask.offsetHeight
}
mask.style.left = X +'px'
mask.style.top = Y +'px'
bigX = -X/(midbox.offsetWidth/bigbox.offsetWidth)
bigY = -Y/(midbox.offsetHeight/bigbox.offsetHeight)
bigboxImg.style.left = bigX +'px'
bigboxImg.style.top = bigY +'px'
})
midbox.addEventListener('mouseout',function(){
mask.style.display = 'none'
bigbox.style.display = 'none'
})
for(let i=0;i<liList.length;i++){
liList[i].addEventListener('mouseover',function(){
midboxImg.src = 'images/pic00'+(i+1)+'.jpg'
bigboxImg.src = 'images/pic0'+(i+1)+'.jpg'
})
}
})
</script>
</html>