当前位置: 首页 > Web前端 > HTML

随意拖动内容位置的两种实现

时间:2023-04-02 22:50:44 HTML

创建时间:2020-03-01;test:chromev80.0.3987.122Normal两种方式分别是:拖拽普通标签的位置或者拖拽文本框在画布中的位置1.实现鼠标拖拽标签元素到任意位置演示地址css代码#range{位置:相对;宽度:600px;高度:400px;边距:10px;背景色:rgb(133,246,250);}.icon{position:absolute;高度:100px;宽度:100px;光标:移动;背景色:#ff9204;user-select:none;}html代码100*100

js代码constmain=document.getElementById('range');consticon=document.querySelector('.icon');letmove=false;letdeltaLeft=0,deltaTop=0;//拖动开始事件,绑定在icon.addEventListener('mousedown',function(e){/**@desdeltaLeft是移动过程中的常量值*/deltaLeft=e.clientX-e.target.offsetLeft;deltaTop=e.clientY-e.target.offsetTop;move=true;})//移动触发事件应该放在区域控制元素上main.addEventListener('mousemove',function(e){if(move){constcx=e.clientX;constcy=e.clientY;/**相减得到相对于父元素的位置*/letdx=cx-deltaLeftletdy=cy-deltaTop/**防止超出父元素的范围*/if(dx<0)dx=0if(dy<0)dy=0if(dx>500)dx=500if(dy>300)dy=300icon.setAttribute('style',`left:${dx}px;top:${dy}px`)}})//拖动结束触发器应该放在区域控件元素上main.addEventListener('mouseup',function(e){move=false;console.log('mouseup');})2.Canvas绘制文本框,并拖动鼠标移动到任意位置csscode.cus-canvas{background:rgb(50,204,243);}.input-ele{display:none;位置:固定;宽度:180px;边界:0;背景色:#fff;}html代码
js代码的原理是记录鼠标移动的位置,不断重绘矩形和文字内容letmouseDown=false;让deltaX=0;letdeltaY=0;lettext='你好'constcanvas=document.getElementById('canvas');constctx=canvas.getCont分机('2d');constcw=canvas.width,ch=canvas.height;constrect={x:20,y:20,width:150,height:50}/**设置文字和边框样式*/ctx.font="16pxArial";ctx.fillStyle="#fff";/**当设置为center时,文本域的中心会在fillText的x点*/ctx.textAlign='center';ctx.lineWidth='2';ctx.strokeStyle='#fff';strokeRect()constinputEle=document.getElementById('inputEle');inputEle.onkeyup=function(e){if(e.keyCode===13){text=inputEle.valuestrokeRect()inputEle.setAttribute('style',`display:none`)}}canvas.ondblclick=function(e){inputEle.setAttribute('style',`left:${e.clientX}px;top:${e.clientY}px;display:block`);inputEle.focus();}canvas.onmousedown=function(e){/**获取视口左边框与画布左边框的距离加鼠标点击的位置和左边框的长度画布,这个值在相对移动时是一个常数值*/deltaX=e.clientX-rect.x;deltaY=e.clientY-rect.y;mouseDown=true};constjudgeW=cw-rect.width,judgeH=ch-rect.height;canvas.onmousemove=function(e){如果(mouseDown){/**相减得到矩形左边框和画布左边框之间的长度*/letdx=e.clientX-deltaX;让dy=e.clientY-deltaY;如果(dx<0){dx=0;}elseif(dx>judgeW){dx=judgeW;}如果(dy<0){dy=0;}elseif(dy>judgeH){dy=judgeH;}rect.x=dx;矩形。y=dy;strokeRect()}};canvas.onmouseup=function(e){mouseDown=false};/**清除指定区域*/functionclearRect(){ctx.clearRect(0,0,cw,ch)}/**画一个矩形*/functionstrokeRect(){clearRect()/**如果不清除在这里调用beginPath,历史矩形会被重绘*/ctx.beginPath()ctx.rect(rect.x,rect.y,rect.width,rect.height)ctx.stroke();//设置画布上的字体内容和位置ctx.fillText(text,rect.x+70,rect.y+30);}欢迎来到Github