创建一个可以拖拽的div,并让鼠标点哪里就从哪里开始拖拽
学习过程中遇到的一个练习题,自己写的时候觉得先行保存固定变量的概念挺有用的
<style>
#show {
width: 100px;
height: 100px;
border: 1px solid black;
background-color: red;
position: absolute;
}
</style>
<script>
var show = document.getElementById("show");
var msg = document.getElementById("show");
show.onmousedown = function(ev) {
var x = ev.clientX;
var y = ev.clientY;//获取鼠标点击时的坐标
var left = x - show.offsetLeft;
var top = y - show.offsetTop;//在鼠标按下时先把鼠标坐标到div边框的距离保存下来
document.onmousemove = function(ev) {
var x = ev.clientX;
var y = ev.clientY;//获取新的鼠标坐标
show.style.left = x - left + "px";
show.style.top = y - top + "px";//用新的坐标减去那段距离
}
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
}
}
</script>
<body>
<div id="show">
</body>