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

原生js放大镜效果实现

2017-04-28 10:24 896 查看
一、先进行文档的一个布局 mask为遮罩部分!
<div id="box">
<div id="small">
<img src="pic.png" width="200" height="200" alt=""/>
<div id="mask"></div>
</div>
<div id="big">
<img id="pic" src="pic.png" width="800" height="850" alt=""/>
</div>
</div>


二、进行一个简单的样式布局
* {
margin: 0;
padding: 0;
}
#small {
position: relative;
float: left;
border: 1px solid black;
text-align: center;
}

#mask {
width: 80px;
height: 80px;
position: absolute;
top: 0;
left: 0;
background:#c40000;
opacity: 0.1;
filter: alpha(opacity=10);
display: none;
}

#big {
width: 350px;
height: 350px;
border: 1px solid black;
float: left;
overflow: hidden;
display: none;
}

三、获取要用到的文档对象

function getId(id) {
return document.getElementById(id)
}
var box = getId("box");
var small = getId("small");
var mask = getId("mask");
var big = getId("big");
var pic = getId("pic");四、进行遮罩部分与大div的显示隐藏
small.onmouseover = function () {
mask.style.display = "block";
big.style.display = "block";
};
small.onmouseout = function () {
mask.style.display = "none";
big.style.display = "none"
};五、设置mask,让其跟随鼠标移动;
small.onmousemove = function (e) {
//
e = e ? e : window.event;
var marginL = small.offsetLeft;//就是相对于其父坐标(body)计算其左侧的位置(左边距)
var marginT = small.offsetTop;
// 得到可视区域的鼠标的坐标
var currentX = e.clientX;
var currentY = e.clientY;
var x = currentX - (marginL + mask.offsetWidth / 2);
var y = currentY - (marginT + mask.offsetHeight / 2);
//       console.log( currentX)
//给mask设置移动区域
if (x < 0) {
x = 0;
}
if (x > small.offsetWidth - mask.offsetWidth) {
x = small.offsetWidth - mask.offsetWidth
}

if (y < 0) {
y = 0;
}
if (y > small.offsetHeight - mask.offsetHeight) {
y = small.offsetHeight - mask.offsetHeight
}

mask.style.left = x + "px";
mask.style.top = y + "px";

六、设置大div中的大图片进行位置的跟随移动

// 方法一:不需要定位
//设置大盒子中显示的内容
var relativeX = mask.offsetLeft;
var relativeY = mask.offsetTop;
console.log(relativeX, relativeY);//mask的移动坐标左上角的轨迹
var proporationX = pic.offsetWidth / small.offsetWidth;
var proporationY = pic.offsetHeight / small.offsetHeight;
console.log(proporationX, proporationY);//大图和小图的倍数
//因为需要移动方向所以为负值 把偏移量乘以倍数得到大图相应的偏移量
pic.style.marginLeft = -relativeX * proporationX + "px";
pic.style.marginTop = -relativeY * proporationY + "px";

方法二:需要进行定位 需要大图相对于父元素(bigdiv)进行绝对定位可以自己加上样式
//找出mask坐标的移动范围的比例
var W = mask.offsetLeft / (small.offsetWidth - mask.offsetWidth);
var H = mask.offsetHeight / (small.offsetHeight - mask.offsetHeight);
//找出big坐标的移动范围的比例 它们的比例是相等的
//var bigW=big.offsetLeft/(pic.offsetWidth-big.offsetWidth);
//var bigH=big.offsetHeight/(pic.offsetHeight-big.offsetHeight);
//console.log(bigw,bigy);
pic.style.left = -(pic.offsetWidth - big.offsetWidth) * W + "px";
pic.style.top = -(pic.offsetHeight - big.offsetHeight) * H + "px";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息