แบบที่จะทำองค์ประกอบ HTML ที่สามารถย้ายได้
- หน้าก่อน จุดส่วนของอุปกรณ์ที่มีนิยายทั่วไป
- หน้าต่อไป JS การขอรับมอบของสื่อ
เรียนรู้ว่าจะใช้ JavaScript และ CSS ทำองค์ประกอบ HTML ที่สามารถย้ายได้
องค์ประกอบ DIV ที่สามารถย้ายได้
คลิกที่นี่เพื่อลาก
ย้าย
นี้
DIV
สร้างองค์ประกอบ DIV ที่สามารถย้ายได้
ขั้นที่ 1 - เพิ่ม HTML:
<!-- DIV ที่ความยาวตั้งแต่ต้น --> <div id="mydiv"> <!-- มีหน้าตัวอย่างแก้ไขตามชื่อ DIV ที่เป็นชื่อเดียวกับ DIV ที่ความยาวตั้งแต่ต้น --> <div id="mydivheader">คลิกที่นี่เพื่อลาก</div> <p>ย้าย</p> <p>นี้</p> <p>DIV</p> </div>
ขั้นที่ 2 - เพิ่ม 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; }
สองขั้นตอนที่สาม - เพิ่ม JavaScript:
// 使 DIV 元素可拖动: dragElement(document.getElementById("mydiv")); function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (document.getElementById(elmnt.id + "header")) { // 如果存在,标题就是您移动 DIV 的位置: document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown; } // 否则,从 DIV 内的任何位置移动 DIV: elmnt.onmousedown = dragMouseDown; } function dragMouseDown(e) { e = e || window.event; e.preventDefault(); // 获取启动时鼠标光标的位置: pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = closeDragElement; // 每当光标移动时调用函数: document.onmousemove = elementDrag; } function elementDrag(e) { e = e || window.event; e.preventDefault(); // 计算新的光标位置: pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // 设置元素的新位置: elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } function closeDragElement() { // 释放鼠标按钮时停止移动: document.onmouseup = null; document.onmousemove = null; } }
- หน้าก่อน จุดส่วนของอุปกรณ์ที่มีนิยายทั่วไป
- หน้าต่อไป JS การขอรับมอบของสื่อ