<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#small{
width:300px;
height: 300px;
background: url(13.jpg);
background-size: 300px 300px;
position: absolute;
left: 100px;
top: 100px;
}
#shade{
width: 100px;
height: 100px;
background: pink;
position: absolute;
opacity: 0.3;
cursor: move;
display: none;
}
#big{
width: 400px;
height: 400px;
background: url(13.jpg);
background-size: 1200px 1200px;
position: absolute;
top: 100px;
left: 450px;
display: none;
}
</style>
</head>
<body>
<div id="small">
<div id="shade"></div>
</div>
<div id="big"></div>
</body>
</html>
<script type="text/javascript">
class MagnifyingGlass{
constructor(newSmall,newBig,newShade) {
this.small = newSmall;
this.big = newBig;
this.shade = newShade;
}
onmouseover(){
let that = this;
this.small.onmouseover=function(evt){
let e = evt || event;
that.big.style.display = "block";
that.shade.style.display = "block";
}
}
onmouseout(){
let that = this;
this.small.onmouseout=function(evt){
let e = evt || event;
that.big.style.display = "none";
that.shade.style.display = "none";
}
}
onmousemove(){
let that = this;
this.small.onmousemove=function(evt){
let e = evt || event;
let left = e.pageX - this.offsetLeft - that.shade.offsetWidth/2;
let top = e.pageY - this.offsetTop - that.shade.offsetHeight/2;
if(left < 0){
left = 0;
}
if(top < 0){
top = 0;
}
let maxLeft = that.small.offsetWidth-that.shade.offsetWidth;
if(left > maxLeft){
left = maxLeft;
}
let maxTop = that.small.offsetHeight-that.shade.offsetHeight;
if(top > maxTop){
top = maxTop;
}
that.shade.style.left=left + "px";
that.shade.style.top=top+ "px";
let x = that.big.offsetWidth*left/that.shade.offsetWidth;
let y = that.big.offsetHeight*top/that.shade.offsetHeight;
console.log(y);
that.big.style.backgroundPositionX = -x + "px";
that.big.style.backgroundPositionY = -y + "px";
}
}
eventBind(){
this.onmouseover();
this.onmouseout();
this.onmousemove();
}
}
let oSmall = document.getElementById("small");
let oBig = document.getElementById("big");
let oShade = document.getElementById("shade");
let oMg = new MagnifyingGlass(oSmall,oBig,oShade);
oMg.eventBind();
</script>
js实现购物车放大镜效果
最新推荐文章于 2023-03-16 13:28:30 发布