<!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>放大镜 面向对象 类</title>
<style>
* {
padding: 0;
margin: 0;
}
html,
body {
position: relative;
}
.small {
width: 420px;
height: 420px;
background: url(images/xiao.jpg) no-repeat;
background-size: 100% 100%;
border: 1px solid black;
position: absolute;
top: 200px;
left: 10px;
}
#box {
width: 210px;
height: 210px;
position: relative;
background: black;
opacity: 0.5;
}
.big {
width: 420px;
height: 420px;
background: url(images/da.jpg) no-repeat;
background-size: 200% 200%;
border: 1px solid black;
position: absolute;
margin-left: 20px;
top: 200px;
left: 500px;
visibility: hidden;
}
</style>
</head>
<body>
<div class="small"></div>
<div class="big"></div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script type="text/javascript">
var $small = $(".small");
var $big = $(".big");
$small.hover(function () {
new MoveBox({ parent: $(".small"), }) //传入父节点,创建对象(小方块)
$big.css("visibility", "visible") //大盒子显示
}, function () {
$("#box").remove() //移除对象
$big.css("visibility", "hidden") //大盒子隐藏
})
class MoveBox {
constructor(options) {
this.options = options;
this.parent = this.options.parent;
this.dom = "";
this.init();
this.move();
}
init() {
this.parent.append($(`<div id="box"></div>`)); //添加节点
this.dom = $("#box"); //获取对象节点
}
move() {
this.parent.mousemove((e) => { //给装小方块的小盒子绑定mousemove事件
var x = e.clientX - this.parent.offset().left - this.dom.width() / 2; //获取移动小方块的left值
var y = e.clientY - this.parent.offset().top - this.dom.height() / 2; //获取移动小方块的top值
this.dom.css({ left: x + 'px', top: y + 'px' });
var maxW = this.parent.width() - this.dom.width() //获取移动的最大宽度
var maxH = this.parent.height() - this.dom.height() //获取移动的最大高度
if (x <= 0) { this.dom.css('left', '0px'); } //限定移动范围
if (x >= maxW) { this.dom.css('left', maxW + 'px'); }
if (y <= 0) { this.dom.css('top', '0px'); }
if (y >= maxH) { this.dom.css('top', maxH + 'px'); }
var lw = this.dom.position().left; //由于上面的限定范围 所以重新获取left,top值
var lh = this.dom.position().top;
$big.css("background-position", lw * -2 + 'px ' + lh * -2 + 'px'); //根据小方块的left top值确定大盒子的背景图片位置
})
}
}
</script>
</html>
小图
大图