放大镜效果
<!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
}
.ibox {
width: 400px;
height: 300px;
position: relative;
border: 1px solid #000;
}
.img {
width: 100%;
height: 100%;
}
.ibox span {
/* width: 133px;
height: 100px; */
display: none;
position: absolute;
left: 0;
top: 0;
background: rgba(200, 200, 200, .5);
}
.pbox {
width: 400px;
height: 300px;
border: 1px solid #000;
position: absolute;
left: 500px;
top: 0;
overflow: hidden;
display: none;
}
.big {
width: 1200px;
height: 900px;
position: absolute;
}
</style>
</head>
<body>
<div class="ibox">
<img src="img/f2.jpg" class="img">
<span></span>
</div>
<div class="pbox">
<img src="img/f2.jpg" class="big">
</div>
</body>
<script>
//面向对象;
// 构造函数创建对象
function Mirror() {
//选择元素;
this.ibox = document.querySelector(".ibox");
this.span = document.querySelector("span");
this.pbox = document.querySelector(".pbox");
this.big = document.querySelector(".big")
//添加事件;
this.addevent();
}
Mirror.prototype.addevent = function() {
//保存this,因为在点击事件的函数里面this不指向new出来的新对象;
let that = this;
console.log(that)
this.ibox.onmouseover = function() {
//鼠标移动显示span和pbox;
that.span.style.display = "block";
that.pbox.style.display = "block";
// console.log(that.span)
// 计算比例设置span的宽高
that.span.style.width = that.pbox.offsetWidth / that.big.offsetWidth * that.ibox.offsetWidth + "px";
that.span.style.height = that.pbox.offsetHeight / that.big.offsetHeight * that.ibox.offsetHeight + "px";
}
this.ibox.onmousemove = function(eve) {
//鼠标移动,span和big跟着移动
var e = eve || window.event;
//边界限定
let l = e.clientX - that.ibox.offsetLeft - that.span.offsetWidth / 2;
let t = e.clientY - that.ibox.offsetTop - that.span.offsetHeight / 2;
if (l < 0) {
l = 0;
}
if (t < 0) {
t = 0;
}
if (l > that.ibox.offsetWidth - that.span.offsetWidth) {
l = that.ibox.offsetWidth - that.span.offsetWidth
}
if (t > that.ibox.offsetHeight - that.span.offsetHeight) {
t = that.ibox.offsetHeight - that.span.offsetHeight
}
that.span.style.left = l + "px";
that.span.style.top = t + "px";
//大图移动距离,要跟span移动的方向相反,所以利用-1取反;
that.big.style.left = -1 * (l / that.ibox.offsetWidth * that.big.offsetWidth) + "px";
that.big.style.top = -1 * (t / that.ibox.offsetHeight * that.big.offsetHeight) + "px"
}
}
new Mirror();
</script>
</html>