一个简单的放大镜
<!DOCTYPE html>
<html>
<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>
</head>
<style>
body{
background-color: #d8e7fa;
}
*{
margin: 0;
padding: 0;
}
ul{
margin: 0;
padding: 0;
list-style: none;
}
.itemarea{
position: relative;
width: 400px;
height: 480px;
border: 1px #888 solid;
margin: 50px auto;
}
.itemarea .pic{
margin-bottom: 15px;
}
.itemarea .pic img{
width: 400px;
height: 400px;
}
.itemarea .pic .cover{
position: absolute;
left: 0;
top: 0;
width: 150px;
height: 150px;
background-image: url(../img/move.png);
}
.itemarea .list{
display: flex;
}
.itemarea .list li{
margin: auto;
}
.itemarea .list img{
display: block;
width: 50px;
height: 50px;
}
.itemarea .detail{
position: absolute;
top: 0;
left: 400px;
width: 400px;
height: 400px;
border: 1px #888 solid;
background-image: url(../img/2.png);
background-size: 267%;
}
.itemarea .list .current{
border: 2px red solid;
}
</style>
<body>
<div class="itemarea">
<div class="pic">
<img src="../img/44.png" alt="">
<div class="cover"></div>
</div>
<ul class="list">
<li>
<img src="../img/44.png" alt="">
</li>
<li>
<img src="../img/3.png" alt="">
</li>
<li>
<img src="../img/4.png" alt="">
</li>
<li>
<img src="../img/2.png" alt="">
</li>
<li>
<img src="../img/3.png" alt="">
</li>
<li>
<img src="../img/4.png" alt="">
</li>
</ul>
<div class="detail">
</div>
</div>
<script>
// 1.需求分析
// 1.1鼠标放在某图片上时,动态修改图片地址
// 1.2鼠标放在大图上时,动态修改右边图片位置
// 1.2.1显示一个区域,用于确认我的鼠标放上去的位置
// 1.2.2显示右边的区域,用于放大图片的展示效果
var list = document.querySelector(".list"),
imgs = list.querySelectorAll('img'),
img = document.querySelector(".pic img"),
pic = document.querySelector('.itemarea .pic'),
cover = document.querySelector('.cover'),
detail= document.querySelector('.detail'),
itemarea =document.querySelector('.itemarea');
list.addEventListener("mousemove",function(e){
if(e.target.tagName =="IMG"){
img.src = e.target.src;
detail.style.backgroundImage='url('+e.target.src+')';
imgs.forEach(function(item){
item.className=';'
})
e.target.className='current';
}
})
pic.addEventListener('mousemove',function(e){
var x =e.clientX,
y =e.clientY;
cx =pic.getBoundingClientRect().left,
cy =pic.getBoundingClientRect().top;
tx =x-cx-75,
ty =y-cy-75;
if(tx<0){
tx=0;
}
if(ty<0){
ty=0;
}
if(tx>itemarea.offsetWidth - cover.offsetWidth - 1){
tx=itemarea.offsetWidth - cover.offsetWidth - 1;
}
if(ty>img.offsetHeight - cover.offsetHeight -1){
ty=img.offsetHeight - cover.offsetHeight -1;
}
detail.style.backgroundPosition = tx/250*100+'%'+ty/250*100+'%';
cover.style.left = tx +'px';
cover.style.top = ty +'px';
})
</script>
</body>
</html>