效果展示:
CSS代码:
<style type="text/css">
#target {
/* 拖动元素的前提是该元素脱离文档流 */
position: absolute;
width: 150px;
height: 80px;
line-height: 80px;
text-align: center;
border: 0;
border-radius: 10px;
background: tomato;
}
</style>
HTML + JavaScript代码:
<div id="target">工具人</div>
<script type="text/javascript">
window.onload = function() {
var target = document.getElementById("target");
document.onmousemove = function(event) {
event = event || window.event; // 兼容不同浏览器
var distanceX = document.body.scrollLeft || document.documentElement.scrollLeft;
var distanceY = document.body.scrollTop || document.documentElement.scrollTop;
target.style.left = event.pageX + distanceX + "px"; // 获取鼠标横向位置的值
target.style.top = event.pageY + distanceY + "px"; // 获取鼠标垂直位置的值
}
}
</script>