Taşınabilir HTML elementi nasıl oluşturulur
- Önceki sayfa Tipik cihaz kesenekleri
- Sonraki sayfa JS medya sorgusu
JavaScript ve CSS kullanarak taşınabilir HTML elementi nasıl oluşturulurunu öğrenin.
taşınabilir DIV elementi
buraya tıklayarak sürükleyin
taşı
bu
DIV
Taşınabilir DIV elementi oluşturun
İlk adım - HTML ekleyin:
<!-- Taşınabilir DIV --> <div id="mydiv"> <!-- Taşınabilir DIV ile aynı adlı bir başlık DIV içerir, ardından "header" --> <div id="mydivheader">buraya tıklayarak sürükleyin</div> <p>taşı</p> <p>bu</p> <p>DIV</p> </div>
İkinci adım - CSS ekleyin:
tek önemli stil position: absolute;
diğer kısımları sizin kararınıza bırakın:
#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; {}
Üçüncü adım - JavaScript ekleyin:
// 使 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; } else { // 否则,从 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; {} {}
- Önceki sayfa Tipik cihaz kesenekleri
- Sonraki sayfa JS medya sorgusu