使用原生js实现京东放大镜的效果,显示如图:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="GBK">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.index {
position: relative;
}
.img {
width: 500px;
height: 500px;
margin: 100px auto 0;
position: relative;
overflow: hidden;
}
.img_img {
width: 100%;
height: 100%;
}
.none_img {
width: 100px;
height: 100px;
background-color: rgba(0,0,0,.2);
position: absolute;
top: 0;
left: 0;
z-index: 2;
display: none;
}
.none {
width: 300px;
height: 300px;
background-color: #ccc;
position: absolute;
top: 0;
right: 20%;
display: none;
}
.none_all {
width: 300px;
height: 300px;
overflow: hidden;
position: relative;
/* background: no-repeat url(https://img2.baidu.com/it/u=4249816449,2447231004&fm=253&fmt=auto&app=138&f=JPEG?w=462&h=500);
background-size: 300%;
background-position-x: 0px;
background-position-y: 0px; */
}
.img1 {
width: 1000px;
height: 1000px;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="index">
<div class="img">
<img class="img_img" src="https://img2.baidu.com/it/u=4249816449,2447231004&fm=253&fmt=auto&app=138&f=JPEG?w=462&h=500" alt="">
<div class="none_img"></div>
</div>
<div class="none">
<div class="none_all">
<img class="img1" src="https://img2.baidu.com/it/u=4249816449,2447231004&fm=253&fmt=auto&app=138&f=JPEG?w=462&h=500" alt="">
</div>
</div>
</div>
<script>
var index=document.querySelector(".index")
var img=document.querySelector(".img")
var none_img=document.querySelector(".none_img")
var none=document.querySelector(".none")
var none_all=document.querySelector(".none_all")
var img1=document.querySelector(".img1")
img.onmouseenter=function() {
none_img.style.display="block"
none.style.display="block"
}
img.onmouseleave=function() {
none_img.style.display="none"
none.style.display="none"
}
img.onmousemove=function(event) {
//图片上的方块
var top=event.pageY - index.offsetTop - none_img.offsetWidth/2
var left=event.pageX - img.offsetLeft - none_img.offsetHeight/2
if(top<0) {
top=0
}
if(top>img.offsetHeight - none_img.offsetHeight) {
top=img.offsetHeight - none_img.offsetHeight
}
if(left<0) {
left=0
}
if(left>img.offsetWidth - none_img.offsetWidth) {
left=img.offsetWidth - none_img.offsetWidth
}
none_img.style.top=top +'px'
none_img.style.left=left +'px'
//图片放大的方块
var top1=event.pageY - index.offsetTop - none_img.offsetWidth/2
if(top1<0) {
top1=0
}
if(top1>200) {
top1=200
}
none.style.top=top1 +'px'
//方块里的图片
var top2=(event.pageY - index.offsetTop)*1.4
var left2=(event.pageX - img.offsetLeft)*1.4
img1.style.top=-top2 +'px'
img1.style.left=-left2 +'px'
}
</script>
</body>
</html>