<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>可拖动的便笺</title> <link rel="stylesheet" href="./css/index.css" /> </head> <body> <div class="note"> <div class="move-bar"></div> <div class="content" contenteditable=""> <p>这是一个便笺</p> <p>里面的文字可以更改</p> <p>用鼠标按住顶部的移动条即可拖动便笺</p> </div> </div> <script src="./js/index.js"></script> </body> </html>
// 让便签可被拖动,但不能超出视口 var note = document.querySelector('.note'); var moveBar = document.querySelector('.move-bar'); moveBar.onmousedown = function(event){ var startX = event.clientX; //鼠标按下的开始 离视口的左边位置 var startY = event.clientY;//鼠标按下的开始 离视口的头部位置 var noteRect = note.getBoundingClientRect(); console.log(noteRect) console.log(note.clientWidth) console.log(note.clientHeight) var maxX = document.documentElement.clientWidth - note.clientWidth; var maxY = document.documentElement.clientHeight - note.clientHeight; window.onmousemove = function(e){ var endX = e.clientX;//鼠标移动 离视口的左边位置 var endY = e.clientY;//鼠标移动 离视口的头部位置 var offsetX = endX - startX; //最终的偏移量 var offsetY = endY - startY; //最终的偏移量 var left = noteRect.left + offsetX; var top = noteRect.top + offsetY; if(left < 0){ left = 0 } if(top<0){ top = 0 } if(left > maxX){ left = maxX; } if(top > maxY){ top = maxY; } // note.style.left = noteRect.left + offsetX + 'px'; // note.style.top = noteRect.top + offsetY + 'px'; note.style.left = left + 'px'; note.style.top = top + 'px'; console.log("startX:"+startX,"startY"+startY,"endX:"+endX,"endY:"+endY,"offsetX:"+offsetX,"offsetY:"+offsetY); console.log("left:"+left,"top:"+top); } window.onmouseup = function(){ //鼠标抬起时清除事件 window.onmousemove = null; window.onmouseup = null; } }
标签:原生,鼠标,拖动,top,js,note,noteRect,var,left From: https://www.cnblogs.com/nianzhilian/p/18454564