您的位置:首页 > Web前端 > JavaScript

基于javascript实现放大镜特效

2020-12-09 04:07 549 查看

本文实例为大家分享了javascript实现放大镜特效的具体代码,供大家参考,具体内容如下

我们在逛pc端商城时,鼠标放到商品上经常会看到一个类似放大镜效果的蒙层,

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
* {
margin: 0px;
padding: 0px;
}

#min {
width: 350px;
height: 350px;
border: 1px solid #ccc;
position: absolute;
left: 50px;
top: 50px;
}

#min img {
width: 350px;
height: 350px;
}

#max {
width: 500px;
height: 500px;
position: absolute;
left: 500px;
top: 50px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}

#max img {
position: absolute;
left: 0;
top: 0;
}

#mask {
width: 200px;
height: 200px;
background: rgba(255, 0, 0, 0.5);
position: absolute;
left: 0px;
top: 0px;
cursor: pointer;
display: none;
}
</style>
</head>

<body>
<div id="min">
<img src="img/min.jpg" alt="" />
<div id="mask"></div>
</div>
<div id="max">
<img src="img/max.jpg" id="maxImg" />
</div>
<script type="text/javascript">
// 1.鼠标经过小盒子,遮罩层出现,大盒子出现
// 2.遮罩层跟随鼠标移动
// 3.遮罩层移动,大盒子里的图片反方向移动
var oMin = document.getElementById('min');
var oMax = document.getElementById('max');
var oMask = document.getElementById('mask');
var oMaxImg = document.getElementById('maxImg');
oMin.onmousemove = function(e) {
// 1.鼠标经过小盒子,遮罩层和大盒子出现
oMask.style.display = 'block';
oMax.style.display = 'block';
// 2.拿到鼠标在小盒子上的坐标
var minX = e.clientX - oMin.offsetLeft;
var minY = e.clientY - oMin.offsetTop;
// 3.将鼠标放置在遮罩层的中间
minX = minX - oMask.offsetWidth / 2;
minY = minY - oMask.offsetHeight / 2;
// 4.遮罩层可以移动的最大距离
var maxWidth = oMin.offsetWidth - oMask.offsetWidth;
var maxHeight = oMin.offsetHeight - oMask.offsetHeight;
// 限定遮罩层的位置
if (minX > maxWidth) {
minX = maxWidth;
} else if (minX <= 0) {
minX = 0;
}
if (minY > maxHeight) {
minY = maxHeight;
} else if (minY <= 0) {
minY = 0;
}
// 设定遮罩层的偏移
oMask.style.left = minX + 'px';
oMask.style.top = minY + 'px';
// 大图片移动的距离=遮罩层移动的距离/遮罩层可以移动的最大距离*大图片最大移动距离
var ratioX = minX / maxWidth;
var ratioY = minY / maxHeight;
// 计算出大图片的移动距离
oMaxImg.style.left = -ratioX * (oMaxImg.offsetWidth - oMax.offsetWidth) + 'px';
oMaxImg.style.top = -ratioY * (oMaxImg.offsetHeight - oMax.offsetHeight) + 'px';
};
// 鼠标移开,遮罩层和大盒子消失
oMin.onmouseout = function() {
oMask.style.display = 'none';
oMax.style.display = 'none';
}
</script>
</body>

</html>

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js 放大镜