<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
width: 300px;
height: 400px;
margin: 100px;
border: 1px solid
}
width: 500px;
height: 500px;
background: url(./img/big/lv-2.png) center;
position: absolute;
box-shadow: 2px 4px 10px
display: none;
}
position: relative;
width: 300px;
height: 300px;
background: url(./img/middle/lv-2.png) 0 /cover;
}
position: absolute;
width: 150px;
height: 150px;
opacity: .4;
left: -1000px;
background: gold;
}
display: flex;
justify-content: space-between;
}
width: 20%;
border: transparent 1px solid;
opacity: .9;
padding: 5px;
}
border:
opacity: 1;
}
</style>
</head>
<body>
<div id="left">
<div id="img">
<div id="shadow">
</div>
</div>
<div id="index">
</div>
</div>
<div id="right">
</div>
</body>
<script>
function $(id) {
return document.getElementById(id)
}
let left = $('left')
let right = $('right')
let shadow = $('shadow')
let img = $('img')
let index = $('index')
//将图片分大小存放在small,middle,big文件中,后期可已控制其他div自动切换图片
let IMG_PATH = 'img'
let arr = ['lv-2.png','lv-3.jpg','lv-4.png','lv-5.png']
//通过forEach创建数组对应数量的img,并切换图片路径
arr.forEach((item,i)=>{
let smallImg = document.createElement('img')
smallImg.src = IMG_PATH +'/small/' + item
index.appendChild(smallImg)
index.children[0].classList.add('active')
smallImg.onmouseenter=e=>{
let active = index.getElementsByClassName('active')[0]
active.classList.remove('active')
smallImg.classList.add('active')
//用replace更改left img和right背景图的路径
let src1 = smallImg.src.replace('small','middle')
let src2 = smallImg.src.replace('small','big')
img.style.backgroundImage = `url(${src1})`
right.style.backgroundImage = `url(${src2})`
}
})
right.style.left = left.offsetLeft + left.offsetWidth + 10 + 'px'
right.style.top = left.offsetTop + 'px'
img.onmousemove = e => {
let x = e.pageX - img.offsetLeft
let y = e.pageY - img.offsetTop
//获取图片左边的鼠标所在位置的百分比赋值到右边背景图的位置
let percentX = x / img.offsetWidth * 100 + '%'
let percentY = y / img.offsetHeight * 100 + '%'
right.style.backgroundPosition = `${percentX} ${percentY}`
//设置跟随鼠标移动的黄色蒙版位置
let shadowX = x - shadow.offsetWidth / 2
let shadowY = y - shadow.offsetHeight / 2
let shadowMaxX = img.offsetWidth - shadow.offsetWidth
let shadowMaxY = img.offsetHeight - shadow.offsetHeight
//使黄色块不超过img区域
if (shadowX <= 0) shadowX = 0
if (shadowY <= 0) shadowY = 0
if(shadowX >= shadowMaxX) shadowX = shadowMaxX
if(shadowY >= shadowMaxY) shadowY = shadowMaxY
shadow.style.left = shadowX + 'px'
shadow.style.top = shadowY + 'px'
}
img.onmouseenter = () => {
right.style.display = 'block'
}
//鼠标移出时黄色块消失,右边的放大镜div消失
img.onmouseleave = () => {
right.style.display = 'none'
shadow.style.left = '-1000px'
}
</script>
</html>