如何创建可拖动的 HTML 元素
学习如何使用 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; }
Tatlong hakbang - Magdagdag ng JavaScript:
// Gawing puwedeng ililipat ang elemento ng DIV: dragElement(document.getElementById("mydiv")); function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (document.getElementById(elmnt.id + "header")) { // Kung mayroon, ang header ay ang lugar na iyong ililipat ang DIV: document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown; } // Kung hindi, ililipat ang DIV mula sa anumang posisyon sa loob ng DIV: elmnt.onmousedown = dragMouseDown; } function dragMouseDown(e) { e = e || window.event; e.preventDefault(); // Kumuha ng posisyon ng mouse cursor sa oras ng pagsisimula: pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = closeDragElement; // Tulungan ang paglipat ng cursor para magsagawa ng function: document.onmousemove = elementDrag; } function elementDrag(e) { e = e || window.event; e.preventDefault(); // Pagkalkula ng bagong posisyon ng cursor: pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // Itatago ang bagong posisyon ng elemento: elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } function closeDragElement() { // Nagpalayas ang paglipat ng mouse button para itigil ang paglipat: document.onmouseup = null; document.onmousemove = null; } }