原生js写放大镜
代码不多,如下:
<!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>放大镜</title>
<style>
.box1,.box2{position: relative;
width: 200px;
height: 200px;
margin-left: 50px;
background-image: url('./image/2.jpg');
float: left;
}
.box1{
background-size: 100% 100%;
}
.box2{
background-repeat: no-repeat;
background-size: 600px 600px;
background-position: 0 0;
}
.little-box{
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: rgba(223, 84, 183, .3)
}
</style>
</head>
<body>
<div class="box1">
<div class="little-box"></div>
</div>
<div class="box2"></div>
<script>
var lb = document.getElementsByClassName('little-box')[0];
var fb = document.getElementsByClassName('box2')[0];
/*鼠标按下*/
lb.onmousedown = function(){
var ev = window.event || ev;
/*鼠标距放大镜左侧的距离 = 鼠标距屏幕左侧的距离-小盒子(放大镜)距屏幕左侧的距离。*/
var xx = ev.clientX - lb.offsetLeft;
/*鼠标距放大镜顶部的距离 = 鼠标距屏幕左侧的顶部-小盒子(放大镜)距屏幕顶部的距离。*/
var yy = ev.clientY - lb.offsetTop;
/*移动鼠标*/
document.onmousemove = function (ev) {
var ev = window.event || ev;
/* 小盒子(放大镜)距屏幕左侧的距离 = 鼠标距屏幕左侧的距离 - 鼠标距放大镜左侧的距离*/
var fdl = ev.clientX - xx ;
/* 小盒子(放大镜)距屏幕顶部的距离 = 鼠标距屏幕顶部的距离 - 鼠标距放大镜顶部的距离*/
var fdt = ev.clientY - yy ;
/*给小盒子设置活动范围*/
if(fdl<0){
fdl=0;
}if(fdl>100){
fdl=100;
}if(fdt<0){
fdt=0;
}if(fdt>100){
fdt=100;
}
lb.style.left = fdl+ "px";
lb.style.top = fdt + "px";
/*放大的图片内容等于小盒子的位置乘于放大的倍数,用的是背景图,所以加一个负号*/
fb.style.backgroundPosition = ((-3*fdl + 'px') +' ' + (-3*fdt + 'px'));
};
/*鼠标抬起时*/
document.onmouseup = function () {
document.onmousemove = document.onmouseup = '';
}
return false;
}
</script>
</body>
</html>
-_-!图片又带水印。。。。大家忽略就好