本文实例为大家分享了JavaScript实现淘宝网图片的局部放大的具体代码,供大家参考,具体内容如下
要实现的效果如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo1</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box{
position: relative;
width: 300px;
height: 200px;
background: url("./JS封面.jpg");
background-size: 300px 200px;
}
.slider{
position: absolute;
width: 100px;
height: 100px;
background: black;
opacity: 0.3;
}
.small{
position: absolute;
width: 100px;
height:100px;
background: url('./JS封面.jpg');
top: 0px;
right: -300px;
background-size: 300px 200px;
transform: scale(3);
}
</style>
</head>
<body>
<div class="box">
<div class="slider"></div>
<div class="small"></div>
</div>
</body>
</html>
<script type="text/javascript">
var slider = document.querySelector('.slider');
var small = document.querySelector('.small');
//鼠标按下
slider.onmousedown = function(event){
var startX = event.offsetX;
var startY = event.offsetY;
//鼠标移动
document.onmousemove = function (event1) {
var l = event1.clientX-startX;
var t = event1.clientY-startY;
//将小滑块限制在大滑块内
if(l <= 0) l = 0;
if(l >= 200) l = 200;
if(t <= 0) t = 0;
if(t >= 100) t = 100;
slider.style.left = l+"px";
slider.style.top = t+"px";
//修改小图的背景图定位
small.style.backgroundPosition="-"+l+"px -"+t+"px";
}
}
//鼠标抬起时,将鼠标移动事件移除
document.onmouseup = function () {
document.onmousemove = null;
}
</script>
代码运行效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。