一直用到div的拖拽,从未自己实现过,今天看了一下,简单写一下,还是可以用的,主要分享给那些和我一样js薄弱的哥们,希望可以帮到你们!!!
<div id="sara_org" style="width:100px;height:100px;background:#058ccc;position:absolute"></div>
<script type="text/javascript">
function sDrag(id) {
var id = id || 'sara';
var m = document.getElementById(id);
var flag = false;
var sX = sY = 0;
m.onmousedown = function(e) {
if (e.button == 0) {
flag = true;
}
sX = e.clientX - m.offsetLeft;
sY = e.clientY - m.offsetTop;
return false
};
document.onmousemove = function(e) {
if (flag == true) {
var x = e.clientX - sX;
var y = e.clientY - sY;
m.style.marginLeft = m.style.marginTop = 0;
m.style.left = x + 'px';
m.style.top = y + 'px';
}
return false;
};
document.onmouseup = function() {
flag = false;
return false;
};
}
$(function() {
sDrag('sara_org');
})
</script>