html布局
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200306201042828.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0FzdXJhVGhvcg==,size_16,color_FFFFFF,t_70)
css效果
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#fdj {
width: 418px;
height: 418px;
position: relative;
}
.small {
background: red;
width: 418px;
height: 418px;
}
.small img {
width: 418px;
height: 418px;
}
.big {
position: absolute;
height: 418px;
width: 418px;
left: 450px;
top: 0;
overflow: hidden;
display: none;
}
.big-img {
position: absolute;
left: 0;
top: 0;
}
.mask {
width: 200px;
height: 200px;
background: rgba(255, 255, 0, 0.3);
position: absolute;
left: 0px;
top: 0px;
display: none;
}
</style>
JS效果实现
<script type="text/javascript">
class Fdj {
constructor(sel) {
this.el = document.querySelector(sel)
this.mask = this.el.querySelector('.mask')
this.small = this.el.querySelector('.small')
this.big = this.el.querySelector('.big')
this.bigImg = this.el.querySelector('.big-img')
let bigImgHeight = parseInt(getComputedStyle(this.big).height) * this.small.offsetHeight / parseInt(
getComputedStyle(this.mask).height)
this.bigImg.style.height = bigImgHeight + 'px';
this.el.onmouseenter = () => {
this.mask.style.display = 'block';
this.big.style.display = 'block';
}
this.el.onmouseleave = () => {
this.mask.style.display = 'none';
this.big.style.display = 'none';
}
this.small.onmousemove = (evt) => {
let x = evt.pageX - this.el.offsetLeft;
let y = evt.pageY - this.el.offsetTop;
let maskX = x - this.mask.offsetWidth / 2;
let maskY = y - this.mask.offsetWidth / 2;
if (maskX <= 0) {
maskX = 0;
}
if (maskX >= this.small.offsetWidth - this.mask.offsetWidth) {
maskX = this.small.offsetWidth - this.mask.offsetWidth;
}
if (maskY >= this.small.offsetWidth - this.mask.offsetWidth) {
maskY = this.small.offsetWidth - this.mask.offsetWidth;
}
if (maskY <= 0) {
maskY = 0;
}
this.mask.style.left = maskX + 'px';
this.mask.style.top = maskY + 'px';
this.bigImg.style.left = -maskX * bigImgHeight / this.small.offsetHeight + 'px';
this.bigImg.style.top = -maskY * bigImgHeight / this.small.offsetHeight + 'px';
}
}
}
new Fdj('#fdj')
</script>