京东放大镜效果(js+css)
移动,放大镜,
·
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="box">
<img src="./img/11.jpg" alt="" class="small" width="100%" height="100%" />
<div class="yy"></div>
<div class="big">
<img src="./img/11.jpg" alt="" />
</div>
</div>
<style>
.box {
position: relative;
width: 350px;
height: 350px;
margin: 20px 200px;
}
.yy {
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
background-color: rgb(203, 233, 248);
opacity: 0.5;
border: 1px solid #333;
display: none;
cursor: move;
}
.big {
position: absolute;
left: 360px;
top: 0px;
width: 300px;
height: 300px;
overflow: hidden;
display: none;
}
.big > img {
position: absolute;
top: 0;
left: 0;
}
</style>
<script>
window.addEventListener('load', function () {
var box = document.querySelector('.box') //最外层盒子
var yy = document.querySelector('.yy') //遮罩层
var big = document.querySelector('.big') //放大的图片
//鼠标移入事件
box.addEventListener('mouseover', function () {
yy.style.display = 'block'
big.style.display = 'block'
})
//鼠标移出事件
box.addEventListener('mouseout', function () {
yy.style.display = 'none'
big.style.display = 'none'
})
//监听鼠标移动事件参数
box.addEventListener('mousemove', function (e) {
//获取到鼠标在图片内部相对偏移量x,y
var x = e.pageX - box.offsetLeft
var y = e.pageY - box.offsetTop
console.log('yy.offsetWidth', yy.offsetWidth)
console.log('yy.offsetHeight', yy.offsetHeight)
//获取到一个相对内部移动范围空间
var width = x - yy.offsetWidth / 2
var height = y - yy.offsetHeight / 2
if (width <= 0) {
width = 0
} else if (width >= box.offsetWidth - yy.offsetWidth) {
width = 200
}
if (height <= 0) {
height = 0
} else if (height >= box.offsetHeight - yy.offsetHeight) {
height = box.offsetHeight - yy.offsetHeight
}
yy.style.left = width + 'px'
yy.style.top = height + 'px'
var bigimg = document.querySelector('.big>img')
// 大图片的移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层最大移动距离
var bigx =
(width * (bigimg.offsetWidth - big.offsetWidth)) /
(box.offsetWidth - yy.offsetWidth)
var bigy =
(height * (bigimg.offsetHeight - big.offsetHeight)) /
(box.offsetHeight - yy.offsetHeight)
bigimg.style.left = -bigx + 'px'
bigimg.style.top = -bigy + 'px'
})
})
</script>
</body>
</html>
仅需要把图片的src改一下即可使用!
更多推荐
所有评论(0)