前天跟着b站的一个老师敲了大概两个小时左右,老师一直说很简单,但是实现的步骤对于接触js时间不太长,或者说连皮毛都不是特别懂的我来说,还是需要多多学习。模板是这个样子,其中参数需要根据添加图片的不同设置不同值,根据自己所需要的页面展示风格,也需要改动相应的margin、position参数,总的来说就是实现三个框架:原图片框、随鼠标移动的半透明矩形框、Details展示框。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>图片放大镜</title>
<style>
body{
background-color:#d8e7fa;
}
ul{
margin:0;
padding:0;
list-style:none;
}
.itemarea{
position:relative;
height:800px;
width:400px;
border:1px#888 solid;
margin:20px auto;
}
.itemarea .pic img{
width:400px;
height:711px;
}
.itemarea .pic .cover{
background-image:url('images/move.png');
opacity:50%;
width:150px;
height:150px;
position:absolute;
left:0;
top:0;
}
.itemarea .list img{
width:35px;
height:60px;
display:block;
}
.itemarea .list{
display:flex;
}
.itemarea .list li{
margin:auto;
}
.itemarea .pic{
margin-bottom:5px;
}
.itemarea .detail{
position:absolute;
display::block;
top:0;
left:400px;
height:711px;
width:400px;
border:1px#888 solid;
background-image:url('images/1.jpg');
background-size:466%;
}
.itemarea .list .current{
border:2px red solid;
}
</style>
</head>
<body>
<div class = 'itemarea'>
<div class = 'pic'>
<img src = "images/1.jpg" alt = "">
<div class = "cover">
</div>
</div>
<ul class = 'list'>
<li>
<img class = 'current' src = "images/1.jpg" alt = "">
</li>
<li>
<img src = "images/2.jpg" alt = "">
</li>
<li>
<img src = "images/3.jpg" alt = "">
</li>
<li>
<img src = "images/4.jpg" alt = "">
</li>
<li>
<img src = "images/5.jpg" alt = "">
</li>
<li>
<img src = "images/6.jpg" alt = "">
</li>
</ul>
<div class = "detail"></div>
</div>
<script>
/* 1.需求分析:鼠标放到某张图片上去的时候动态修改图片地址
2.鼠标放到大图的时候,动态修改右边图片位置
1.2.1显示一个区域 用于确认鼠标放上去的位置
1.2.2显示右边区域用于放大图片的展示效果
window/documentaq
*/
/*图片切换实现 list*/
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');
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;
//console.log(e.clientX,e.clientY);
//console.log(cx,cy);/*获取页面当中元素位置*/
if(tx<0){
tx = 0;
}
if(ty<0){
ty = 0;
}
if(tx>250){
tx = 250;
}
if(ty>561){
ty = 561;
}
detail.style.backgroundPosition = tx/250*100+'%'+ty/561*100+'%';
cover.style.left =tx+'px';
cover.style.top = ty+'px';
})
/*for(var i = 0;i<list.length;i++)
{
list[i].onmouseover = (function(j){
console.log(list[j],i);
})(i)
}*/
/*图片:1920*1080 展示框:600*400 小框:150*150 */
</script>
</body>
</html>