全文不想说废话!!!!
在淘宝、京东等电商网站上,点开商品详情页,鼠标移到商品图片上显示的图片放大效果。
html代码
<body>
<div id="demo">
<div id="small-box">
<div id="float-box"></div>
<img src="macbook-small.jpg" alt="macbook-small.jpg">
</div>
<div id="big-box">
<img src="macbook-big.jpg" alt="macbook-big.jpg">
</div>
</div>
</body>
css代码
<style type="text/css">
#demo {
overflow: hidden;
font-size: 0;
}
#small-box {
position: relative;
width: 400px;
border: 4px solid #b4b4b4;
float: left;
padding: 0;
}
#small-box>img {
width: 100%;
margin: 0;
}
#float-box {
display: none;
width: 200px;
height: 100px;
position: absolute;
background: #ffffcc;
border: 1px solid #ccc;
filter: alpha(opacity=50);
opacity: 0.5;
cursor: pointer;
padding: 0;
margin: 0;
}
#big-box {
display: none;
position: relative;
width: 600px;
height: 300px;
border: 10px solid #b4b4b4;
float: left;
margin-left: 20px;
overflow: hidden;
}
#big-box>img {
position: absolute;
}
</style>
JS代码
window.onload = function () {
let objDemo = document.getElementById("demo");
let objSmallBox = document.getElementById("small-box")
let objFloatBox = document.getElementById("float-box")
let objBigBox = document.getElementById("big-box")
let objBigBoxImage = document.getElementsByTagName("img")[1]
objSmallBox.addEventListener('mouseover', function () {
objFloatBox.style.display = "block";
objBigBox.style.display = 'block';
})
objSmallBox.addEventListener('mouseout', function () {
objFloatBox.style.display = "none";
objBigBox.style.display = 'none';
})
objSmallBox.addEventListener('mousemove', function (ev) {
let _event = ev;
var left = _event.clientX - objDemo.offsetLeft - objSmallBox.offsetLeft - objFloatBox.offsetWidth / 2
var top = _event.clientY - objDemo.offsetTop - objSmallBox.offsetTop - objSmallBox.clientTop - objFloatBox.offsetHeight / 2;
if (left < 0) {
left = 0
} else if (left > (objSmallBox.clientWidth - objFloatBox.offsetWidth)) {
left = objSmallBox.clientWidth - objFloatBox.offsetWidth
}
if (top < 0) {
top = 0
} else if (top > (objSmallBox.clientHeight - objFloatBox.offsetHeight)) {
top = objSmallBox.clientHeight - objFloatBox.offsetHeight
}
objFloatBox.style.left = left + 'px';
objFloatBox.style.top = top + 'px';
var proportion = objFloatBox.offsetWidth / objBigBox.offsetWidth;
var percentX = left / proportion;
var percentY = top / proportion;
objBigBoxImage.style.left = -percentX + 'px';
objBigBoxImage.style.top = -percentY + 'px';
})
}