js原生拖拽框架
程序员文章站
2022-07-14 16:45:10
...
js原生拖拽框架
模板对象.onmousedown = function(){
console.log('按下');
document.onmousemove = function(){
console.log('移动');
}
document.onmouseup = function(){
console.log('松开');
//松开后,记得解绑移动事件
document.onmousemove = null;
}
}
简单的方块拖动算法一
<style>
#box{
position: fixed;
width: 100px;
height: 100px;
background-color:red;
}
</style>
<div id="box"></div>
<script>
var box = document.getElementById('box');
box.onmousedown = function( event ){
var distX = event.clientX - box.offsetLeft;
var distY = event.clientY - box.offsetTop;
var maxLeft = window.innerWidth - box.offsetWidth;
var maxTop = window.innerHeight - box.offsetHeight;
document.onmousemove = function(event){
var x = event.clientX - distX;
if( x<=0 ) x = 0;
if(x>=maxLeft) x = maxLeft;
var y = event.clientY - distY;
if(y<=0)y=0;
if(y>=maxTop)y = maxTop;
box.style.left = x + 'px';
box.style.top = y + 'px';
}
document.onmouseup = function(){
// console.log('松开');
//松开之后清空移动事件,避免松开还能拖
document.onmousemove = null;
}
}
</script>
简单方块拖拽算法二
<style>
#box{
position: fixed;
width: 100px;
height: 100px;
background-color:red;
}
</style>
<div id="box"></div>
<script>
var box = document.getElementById('box');
box.onmousedown = function( event ){
var boxLeft = box.offsetLeft;
var boxTop = box.offsetTop;
var startX = event.clientX;
var startY = event.clientY;
var maxLeft = window.innerWidth - box.offsetWidth;
var maxTop = window.innerHeight - box.offsetHeight;
document.onmousemove = function(event){
var endX = event.clientX;
var endY = event.clientY;
var distX = endX - startX;
var distY = endY - startY;
var left = boxLeft + distX;
var top = boxTop + distY;
box.style.left = left + 'px';
box.style.top = top + 'px';
}
document.onmouseup = function(){
document.onmousemove = null;
}
}
</script>
计算尺寸
-
window.innerWidth
:获取屏幕可视宽 -
window.innerHeight
:获取屏幕可视高 -
dom对象.offsetLeft
:获取对象的左偏移值 -
dom对象.offsetTop
:获取对象的顶偏移值 -
dom对象.offsetWidth
:获取对象的宽度(包含边框、填充、滚动条) -
dom对象.offsetHeight
:获取对象的高度(包含边框、填充、滚动条) -
event.clientX
: 获取对象距屏幕左侧边缘X坐标 -
event.clientY
: 获取对象距屏幕顶部侧边缘Y坐标
特别注意:当
display:none
时,那么使用offsetWidth
或者offsetHeight
取不到它的宽度和高度,返回数值0,解决方案可以使用visibility:hidden
,这样可以获取值。
window对象
获取可视宽、可视高
window.innerHeight
,window.innerWidth
上一篇: js拖拽元素互换位置
下一篇: 原生JS实现Div拖拽