新版拖拽 ,并且支持放大缩小
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
<meta name="referrer" content="never">
<title>test</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
.process{
position: relative;
width: 300px;
height: 30px;
margin: 50px;
background-color: #f0f;
}
.line{
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #f00;
}
.box{
position: relative;
width: 500px;
height: 500px;
margin: 100px auto;
background-color: #ffa600;
}
.mirror{
position: absolute;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
background-color: #9000ff;
border-radius: 50%;
}
</style>
</head>
<body>
<div class="process"><div class="line"></div></div>
<p class="text" style="text-indent: 50px;">放大比例: <span>100%</span></p>
<div class="box">
<div class="mirror"></div>
</div>
<script type="text/javascript">
// get elements & some variable
let mirror = document.querySelector(".mirror"),
box = document.querySelector(".box");
process = document.querySelector(".process"),
line = document.querySelector(".line"),
record = document.querySelector(".text span"),
bite = 100, // scale bite
max = {
x: box.offsetWidth - mirror.offsetWidth,
y: box.offsetHeight - mirror.offsetHeight
}; // min -> 0,0 max -> bounding
// scale to big
process.onmousedown = function (){
this.onmousemove = function (){
// record mouse distance from process
let v = event.pageX - this.offsetLeft;
// assignment line width
line.style.width = v + "px";
// record zoom bite
bite = Math.ceil(v/this.offsetWidth * 100 + 100)
record.innerText = bite + "%";
// zoom boxElement
box.style.transform = `scale(${ parseFloat(bite/100) })`;
}
this.onmouseup = () => this.onmousemove = null;
}
mirror.onmousedown = function (){
// 获取按下时鼠标与元素的距离 排除缩放即可
let mirrorBcr = this.getBoundingClientRect();
let boxBcr = box.getBoundingClientRect();
console.log(mirrorBcr,boxBcr)
// 元素放大 -> 调整鼠标与元素距离
let mouse = {
x: event.pageX - mirrorBcr.x,
y: event.pageY - mirrorBcr.y
}
window.onmousemove = function (){
/* 用鼠标与页面的距离 - box与页面的距离 - 鼠标与镜子的距离 = 镜子与页面的距离
元素放大 =>
鼠标与页面的距离不变
调整box与页面的距离
鼠标移动的距离放大 -> 需要缩小
max 不会改变
*/
let move = new Proxy({
l: event.pageX - boxBcr.x - mouse.x,
t: event.pageY - boxBcr.y - mouse.y
}, {
get(t, p){
console.log('t',t,'p',p)
let target = t[p] / bite * 100;
target = Math.min(Math.max(0,target), max[p == "l" ? "x" : "y"]);
return target;
}
})
mirror.style.cssText = `top: ${ move.t }px;left: ${ move.l }px;`;
}
window.onmouseup = () => window.onmousemove = null;
}
</script>
</body>
</html>