首先先建立一个div。
1 var elem = document.createElement('div'); 2 elem.style.height = '100px'; 3 elem.style.width = '100px'; 4 elem.style.backgroundColor = '#ff0'; 5 document.body.appendChild(elem);
给元素附加onmousedown事件,这个onmousedown事件又会触发document的onmousemove事件,document的时间用来捕捉到鼠标的坐标,然后把坐标赋给elem的left和top。元素onmouseup事件会把document的onmousemove事件清空(通过赋值为null)。所以元素会停留在松开鼠标的位置。
1 elem.onmousedown = function (){ 2 this.style.position = 'absolute'; 3 document.onmousemove = function (e){ 4 elem.style.left = e.pageX - parseInt(elem.style.width)/2; 5 elem.style.top = e.pageY - parseInt(elem.style.height)/2; 6 } 7 } 8 document.onmouseup = function (){ 9 document.onmousemove = null; 10 }