Demo 在线地址:
https://sx00xs.github.io/test/44/index.html
---------------------------------------------------------------
ide: vscode
文件格式:.vue
解析:(待补)
<template> <div class="box" ref="myBox" > <h2 @mousedown="handleDown" @mousemove="handleMove" @mouseup="handleUp" > <a href="javascript:;" @click="handleClick" @mousedown="handleAdown" >点击回放拖动轨迹</a> </h2> <p><strong>Drag:</strong><span>{{ bDrag }}</span></p> <p><strong>offsetTop:</strong><span>{{ span1 }}</span></p> <p><strong>offsetLeft:</strong><span>{{ span2 }}</span></p> </div> </template> <script> import { setInterval, clearInterval } from 'timers'; export default { name:'Mavs', data(){ return{ bDrag:false, span1:'', span2:'', disX:0, disY:0, pos:[ {x:'', y:''} ] } }, methods:{ handleInitlalSpan(){ var elem = this.$refs.myBox; this.span1=elem.offsetTop; this.span2=elem.offsetLeft; }, handleDown(){ var elem = this.$refs.myBox; this.bDrag=true; this.disX = event.clientX - elem.offsetLeft;; this.disY = event.clientY - elem.offsetTop; //console.log(this.disX); //console.log(this.disY); this.pos.push({x:elem.offsetLeft, y:elem.offsetTop}); return false; }, handleMove(){ if(!this.bDrag) return; var elem = this.$refs.myBox; var iL = event.clientX - this.disX; var iT = event.clientY - this.disY; var maxL = document.documentElement.clientWidth - elem.offsetWidth; var maxT = document.documentElement.clientHeight - elem.offsetHeight; iL = iL < 0 ? 0 : iL; iL = iL > maxL ? maxL : iL; iT = iT < 0 ? 0 : iT; iT = iT > maxT ? maxT : iT; elem.style.marginTop = 0; elem.style.marginLeft = 0; elem.style.left = iL + 'px'; elem.style.top = iT + 'px'; this.pos.push({x:iL, y:iT}); this.span1=elem.offsetTop; this.span2 = elem.offsetLeft; }, handleUp(){ var elem = this.$refs.myBox; this.bDrag=false; this.span1=elem.offsetTop; this.span2 = elem.offsetLeft; }, handleClick(){ var _this=this; var elem = this.$refs.myBox; if(this.pos.length == 1) return; var timer=setInterval(function(){ var myPos=_this.pos.pop(); myPos ? (elem.style.left = myPos.x + 'px', elem.style.top = myPos.y + 'px',_this.status()) : clearInterval(timer) },30); }, handleAdown(){ event.cancelBubble=true }, status(){ var elem=this.$refs.myBox; this.span1=elem.offsetTop; this.span2=elem.offsetLeft; } }, mounted(){ this.handleInitlalSpan() document.addEventListener('mousemove',this.handleMove) } } </script>