HTML
<div class="itemrea">
<div class="pic">
<img src="./img/素材01.jpeg" alt=""> //自己随便换图片
<div class="cover" style="display: none;"></div>
</div>
<div class="detail" style="display: none;">
<img src="./img/素材01.jpeg" alt="">
</div>
</div>
CSS结构
<style>
body {
background-color: #d8e7fa;
}
* {
margin: 0;
padding: 0;
list-style: none;
}
.itemrea {
position: relative;
width: 400px;
height: 400px;
border: 1px #888 solid;
margin: 100px auto;
}
.itemrea .pic img {
width: 400px;
height: 400px;
}
.itemrea .pic .cover {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: rgba(200, 200, 200, 0.6);
}
.itemrea .detail {
position: absolute;
top: 0;
left: 420px;
width: 400px;
height: 400px;
border: 1px #888 solid;
overflow: hidden;
}
.itemrea .detail img {
width: 1600px; /* 这里高和宽 是用遮罩层的宽度 100 除以 左边框的高度 是 400 然后 用右边框的高度400 除以 0.25 = 1600px。 400/(100/400)=1600 */
height: 1600px;
position: absolute;
left: 0;
top: 0;
}
</style>
JS结构
<script>
var pic = document.querySelector(".itemrea .pic"),
cover = document.querySelector(".cover"),
detail = document.querySelector(".detail"),
img = document.querySelector('.detail img');
pic.addEventListener("mouseover", function (e) {
cover.style.display = 'block'
detail.style.display = 'block'
})
pic.addEventListener("mouseout", function (e) {
cover.style.display = 'none'
detail.style.display = 'none'
})
pic.addEventListener('mousemove', function (e) {
//e.clientX - pic.getBoundingClientRect().left 鼠标距离左边框的左侧距离 cover.offsetWidth/2 遮罩层宽度一半 mouseLeft算出鼠标在遮罩层中心的点
var mouseLeft = e.clientX - pic.getBoundingClientRect().left - cover.offsetWidth / 2,
mouseTop = e.clientY - pic.getBoundingClientRect().top - cover.offsetHeight / 2;
//判断左边界 不让遮罩层出框
if (mouseLeft <= 0) {
mouseLeft = 0
}
//判断上边界 不让遮罩层出框
if (mouseTop <= 0) {
mouseTop = 0
}
//判断右边界 不让遮罩层出框
//pic.offsetWidth 获取左边框的宽度
if (mouseLeft >= pic.offsetWidth - cover.offsetWidth) {
mouseLeft = pic.offsetWidth - cover.offsetWidth
}
//判断下边界 不让遮罩层出框
if (mouseTop >= pic.offsetHeight - cover.offsetHeight) {
mouseTop = pic.offsetHeight - cover.offsetHeight
}
cover.style.left = mouseLeft + 'px'
cover.style.top = mouseTop + 'px'
//这行代码实现了右边放大的效果
img.style.left = - (img.offsetWidth * (mouseLeft / pic.offsetWidth)) + 'px'
img.style.top = - (img.offsetHeight * (mouseTop / pic.offsetHeight)) + 'px'
})
</script>
js原生放大镜
最新推荐文章于 2024-05-08 07:28:03 发布