1.html
<div id="test"></div>
2.css
#test {
width: 100px;
height: 100px;
background: #000;
position: absolute;
color: #fff;
cursor: pointer;
outline: none;
}
3.js
(function() {
function Code() {}
Code.prototype = {
addEvent: function() {
var that = this;
var oDiv = document.getElementById('test');//与html要拖拽的元素id名相同
oDiv.onmousedown = function(ev) {
var ev = ev || event;
var distanceX = ev.clientX - this.offsetLeft;
var distanceY = ev.clientY - this.offsetTop;
if (oDiv.setCapture) {
oDiv.setCapture();
}
document.onmousemove = function(ev) {
var ev = ev || event;
oDiv.style.left = ev.clientX - distanceX + 'px';
oDiv.style.top = ev.clientY - distanceY + 'px';
};
document.onmouseup = function(ev) {
document.onmousemove = document.onmouseup = null;
if (oDiv.releaseCapture) {
oDiv.releaseCapture();
}
};
};
},
init: function() {
var that = this;
window.onload = that.addEvent;
},
}
new Code().init();
})();
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。