js原生实现元素跟随鼠标拖动


var ele = document.getElementById('box')
document.onmousemove = function (e) {
// 处理兼容
e = e || window.e
// 不考虑IE8及以下
var left = e.pageX
var top = e.pageY
// 需要设置单位
ele.style.left = left + 'px'
ele.style.top = top + 'px'
}

 


document.onmousemove = function (e) {
e = e || window.e
// 处理兼容
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop
var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft
var left = e.clinetX
var top = e.clientY
ele.style.left = left + scrollLeft + 'px'
ele.style.top = top + scrollTop + 'px'
}

posted on 2020-03-21 11:18  daV_chen  阅读(883)  评论(0编辑  收藏  举报

导航