本篇文章为大家展示了使用js实现一个淘宝浏览商品放大镜功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
1、准备两张图片,其中一张图片分辨率为另一张图片的二倍。
2、前端页面布局
//box1位左侧原图,box2为右侧放大图额显示框,son为iv class="box1">
<div class="son"></div>
<div class="ceng"></div>
</div>
<div class="box2"></div>
3、js写逻辑
let box1=document.querySelector(".box1");
let box2=document.querySelector(".box2");
let son=document.querySelector(".son");
let ceng=document.querySelector(".ceng");
//鼠标移入:son,box2出现
ceng.onmouseenter=function(){
son.style.display="block"
box2.style.display="block"
}
//鼠标移出:son,box2消失
ceng.onmouseleave=function(){
son.style.display="none"
box2.style.display="none"
}
//鼠标移动:son的位置随鼠标移动,box2背景图的位置变化
ceng.onmousemove=function(e){
let sw=e.clientX-son.offsetWidth/2
let sh=e.clientY-son.offsetHeight/2
if(sw>ceng.offsetWidth-son.offsetWidth){
sw=ceng.offsetWidth-son.offsetWidth
}
else if(sw<=0){
sw=0;
}
if(sh>ceng.offsetHeight-son.offsetHeight){
sh=ceng.offsetHeight-son.offHeight
}
else if(sh<=0){
sh=0;
}
son.style.left=sw+"px"
son.style.top=sh+"px"
box2.style.backgroundPosition=`${-2*sw}px ${-2*sh}px`
}
完整代码
<!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>
</head>
<style>
*{
margin: 0;
padding: 0;
}
.box1{
width: 500px;
height:333px;
/* border:1px solid red; */
background: url('shatan.jpg') no-repeat;
position: relative;
float: left;
box-sizing: border-box
}
.son{
width: 100px;
height: 100px;
background-color: #fff;
position: fixed;
left:0;
top:0;
opacity: 0.7;
display: none;
}
.ceng{
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 100;
}
.box2{
width: 200px;
height:200px;
border:1px solid red;
background: url('shatan1.jpg') no-repeat;
float: left;
display: none;
}
</style>
<body>
<div class="box1">
<div class="son"></div>
<div class="ceng"></div>
</div>
<div class="box2"></div>
</body>
</html>
<script>
let box1=document.querySelector(".box1");
let box2=document.querySelector(".box2");
let son=document.querySelector(".son");
let ceng=document.querySelector(".ceng");
ceng.onmouseenter=function(){
son.style.display="block"
box2.style.display="block"
}
ceng.onmouseleave=function(){
son.style.display="none"
box2.style.display="none"
}
ceng.onmousemove=function(e){
let sw=e.clientX-son.offsetWidth/2
let sh=e.clientY-son.offsetHeight/2
if(sw>ceng.offsetWidth-son.offsetWidth){
sw=ceng.offsetWidth-son.offsetWidth
}
else if(sw<=0){
sw=0;
}
if(sh>ceng.offsetHeight-son.offsetHeight){
sh=ceng.offsetHeight-son.offHeight
}
else if(sh<=0){
sh=0;
}
son.style.left=sw+"px"
son.style.top=sh+"px"
box2.style.backgroundPosition=`${-2*sw}px ${-2*sh}px`
}
</script>
上述内容就是使用js实现一个淘宝浏览商品放大镜功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。