2021-01-28 10:42发布
html>
lang="en">
charset="UTF-8">
name="viewport" content="width=device-width, initial-scale=1.0">
Document
*{
padding: 0;
margin: 0;
}
#box{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
left: 50px;
top: 50px;
id="box">
[removed]
// 拖拽的三个状态
// 按下 移动 抬起
// 鼠标移动过快离开了div 这个时候鼠标移动事件就不触发了 但是离不开整个文档
var box = document.getElementById("box");
// 鼠标按下去
box.onmousedown = function(ev){
ev = ev || window.event;
// 获取数鼠标距离拖拽元素的距离
var x = ev.clientX - box.offsetLeft;
var y = ev.clientY - box.offsetTop;
// 鼠标移动
[removed] = function(ev){
// 在移动过程中获取最新的left值和top值
var left = ev.clientX - x;
var top = ev.clientY - y;
// 给box进行赋值
box.style.left = left + 'px';
box.style.top = top + 'px';
// 鼠标抬起
[removed] = function(){
// 将鼠标移动和鼠标抬起都移除
[removed] = [removed] = null;
最多设置5个标签!
html>
lang="en">
charset="UTF-8">
name="viewport" content="width=device-width, initial-scale=1.0">
*{
padding: 0;
margin: 0;
}
#box{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
left: 50px;
top: 50px;
}
[removed]
// 拖拽的三个状态
// 按下 移动 抬起
// 鼠标移动过快离开了div 这个时候鼠标移动事件就不触发了 但是离不开整个文档
var box = document.getElementById("box");
// 鼠标按下去
box.onmousedown = function(ev){
ev = ev || window.event;
// 获取数鼠标距离拖拽元素的距离
var x = ev.clientX - box.offsetLeft;
var y = ev.clientY - box.offsetTop;
// 鼠标移动
[removed] = function(ev){
ev = ev || window.event;
// 在移动过程中获取最新的left值和top值
var left = ev.clientX - x;
var top = ev.clientY - y;
// 给box进行赋值
box.style.left = left + 'px';
box.style.top = top + 'px';
}
// 鼠标抬起
[removed] = function(){
// 将鼠标移动和鼠标抬起都移除
[removed] = [removed] = null;
}
}
[removed]
一周热门 更多>