一、拖拽的流程動做html
二、注意事項:html5
三、代碼實現:瀏覽器
html:app
<div id='box' style="position:relative;width:100px;height:100px;background:#ee735c;"> <!--爲了設置left、top,需相對或絕對定位--> 可拖動div元素 </div>
js:spa
window.onload = function() { var box = document.getElementById('box') box.onmousedown = function(e) { //首先要獲取鼠標相對於元素的位置 var disX = e.clientX - box.offsetLeft //clientX,Y鼠標相對於瀏覽器窗口可視區域的X,Y座標(窗口座標) var disY = e.clientY - box.offsetTop //offsetLeft,top是元素相對父元素的偏移寬度 document.onmousemove = function(e) { var l = e.clientX - disX var t = e.clientY - disY if(l < 0) { //防止div跑出可視框 l = 0; } else if(l > document.documentElement.clientWidth - box.offsetWidth) { l = document.documentElement.clientWidth - box.offsetWidth; } if(t < 0) { t = 0; } else if(t > document.documentElement.clientHeight - box.offsetHeight) { t = document.documentElement.clientHeight - box.offsetHeight; } box.style.left = l + 'px'; box.style.top = t + 'px'; } document.onmouseup = function() { document.onmousemove = null; document.onmouseup = null } return false } }
拖放是html5的標準,任何元素都可以拖放code
html:htm
<div class="div1" ondrop="drop(event)" ondragover="allowDrop(event)"> <img src="img/2.jpg" draggable="true" ondragstart="drag(event)" id="drag1" /> //設置元素可拖放 </div> <div class="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
js:blog
function drag(ev) { //ondragstart拖動開始 ev.dataTransfer.setData("ok", ev.target.id); //設置元素屬性 } function allowDrop(ev) { //ondragover拖動結束 ev.preventDefault(); //默認不準放置,阻止默認 } function drop(ev) { //ondrop放置 ev.preventDefault(); var data = ev.dataTransfer.getData("ok"); //加入元素 ev.target.appendChild(document.getElementById(data)); }