模仿部分电商网站放大镜行为,在一个盒子中对小盒子进行拖拽
HTML
<div class="big">
<div class="small"></div>
</div>
css
.big{
width: 600px;
height: 600px;
border: 1px solid #999;
position: relative;
margin: auto;
}
.small{
height: 100px;
width: 100px;
background-color: blueviolet;
position: absolute;
}
js
var big = document.querySelector('.big')
var small = document.querySelector('.small')
small.onmousedown = function(e){
var e = e || window.event
var x = e.offsetX
var y = e.offsetY
small.onmousemove = function(e){
console.log(big.offsetTop);
var e = e || window.event
var x1 = e.clientX
var y1 = e.clientY
var l = x1 - x - big.offsetLeft
var t = y1 - y - big.offsetTop
if(l<=0){
l = 0
}
if(t<=0){
t = 0
}
if(l>=big.clientWidth - small.clientWidth){
l = big.clientWidth - small.clientWidth
}
if(t>=big.clientHeight - small.clientHeight){
t = big.clientHeight - small.clientHeight
}
small.style.top = t +'px'
small.style.left = l + 'px'
}
}
document.onmouseup = function(){
big.onmousemove = null
}