js实现淘宝京东购物网站商城商品的鼠标经过放大镜效果
<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.wrap {
width: 250px;
height: 250px;
position: relative;
margin-left: 100px;
margin-top: 100px;
}
.inner {
width: 150px;
height: 150px;
background-color: rgba(0, 0, 0, 0.5);
position: absolute;
top: 0;
left: 0;
display: none;
}
.big {
width: 300px;
height: 300px;
position: absolute;
left: 270px;
top: -20px;
overflow: hidden;
display: none;
}
</style>
</head>
<body>
<div class="wrap">
<img src="rp4.png" alt="">
<div class="inner"></div>
<div class="big">
<img src="rp41.png" alt="">
</div>
</div>
<script>
var wrap = document.querySelector('.wrap');
var inner = document.querySelector('.inner');
var big = document.querySelector('.big');
var bigImg = document.querySelector('.big img');
wrap.onmousemove = function (e) {
var e = window.event || e;
var left = e.clientX - inner.offsetWidth / 2 - wrap.offsetLeft;
var top = e.clientY - inner.offsetHeight / 2 - wrap.offsetTop;
var bigWidth = wrap.offsetWidth - inner.offsetWidth;
var bigHeight = wrap.offsetHeight - inner.offsetHeight;
if (left > bigWidth) {
left = bigWidth;
}
if (left < 0) {
left = 0;
}
if (top > bigHeight) {
top = bigHeight;
}
if (top < 0) {
top = 0;
}
inner.style.left = left + "px";
inner.style.top = top + 'px';
bigImg.style.marginLeft = -500 / 250 * inner.offsetLeft + 'px';
bigImg.style.marginTop = -500 / 250 * inner.offsetTop + 'px';
}
wrap.onmouseenter = function () {
inner.style.display = 'block';
big.style.display = 'block';
}
wrap.onmouseleave = function () {
inner.style.display = 'none';
big.style.display = 'none';
}
</script>
</body>
</html>