如何创建可拖动的 HTML 元素
- Previous page Typical device breakpoint
- Next page JS media query
学习如何使用 JavaScript 和 CSS 创建可拖动的 HTML 元素。
可拖动的 DIV 元素
点击这里拖动
移动
这个
DIV
创建可拖动的 DIV 元素
第一步 - 添加 HTML:
<!-- 可拖动的DIV --> <div id="mydiv"> <!-- 包含一个与可拖动 DIV 同名的标题 DIV,后跟 "header" --> <div id="mydivheader">点击这里拖动</div> <p>移动</p> <p>这个</p> <p>DIV</p> </div>
第二步 - 添加 CSS:
唯一重要的样式是 position:absolute
,其余部分由您决定:
#mydiv { position: absolute; z-index: 9; background-color: #f1f1f1; border: 1px solid #d3d3d3; text-align: center; {} #mydivheader { padding: 10px; cursor: move; z-index: 10; background-color: #2196F3; color: #fff; {}
Third step - Add JavaScript:
// Make the DIV element draggable: dragElement(document.getElementById("mydiv")); function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (document.getElementById(elmnt.id + "header")) { // If the title exists, it is the position where you move the DIV: document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown; } // Otherwise, move the DIV from any position inside the DIV: elmnt.onmousedown = dragMouseDown; {} function dragMouseDown(e) { e = e || window.event; e.preventDefault(); // Get the position of the mouse cursor at the start: pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = closeDragElement; // Call the function every time the cursor moves: document.onmousemove = elementDrag; {} function elementDrag(e) { e = e || window.event; e.preventDefault(); // Calculate the new cursor position: pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // Set the new position of the element: elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; {} function closeDragElement() { // When the mouse button is released, stop moving: document.onmouseup = null; document.onmousemove = null; {} {}
- Previous page Typical device breakpoint
- Next page JS media query