鼠标拖拽效果

本次编写结果


代码展示:<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
position: absolute;
width: 40rem;
height: 30rem;
background-color: yellow;
}
</style>
</head>

<body>
<div id="box"></div>
<script>
let box = document.getElementById("box")
//鼠标在box上左键按下时;拖动
box.onmousedown = function (e) {
let offsetX = e.offsetX
let offsetY = e.offsetY
console.log(offsetX, "offsetX")
console.log(offsetY, "offsetY")
//鼠标在窗口中移动
document.onmousemove = function (e2) {
let clientX = e2.clientX
let clientY = e2.clientY
console.log(clientX, "clientX")
console.log(clientY, "clientY")
//计算div位置
_left = clientX - offsetX//水平
_top = clientY - offsetY //数值
console.log(_left, "left")
console.log(_top, "top")
//左边界判断
if(_left < 0){
_left = 0;
}
//上边界判断
if(_top < 0){
_top = 0
}
//有边界判断
if(_left > document.documentElement.clientWidth - box.offsetWidth){
_left = document.documentElement.clientWidth - box.offsetWidth
}
//下边界判断
if(_top > document.documentElement.clientHeight - box.offsetHeight){
_top = document.documentElement.clientHeight - box.offsetHeight
}

            //定位div位置
            box.style.left = _left + "px"
            box.style.top = _top + "px"
        }
    }
    //鼠标抬起接触
    document.onmouseup = function () {
        //解除移动
        document.onmousemove = null
    }
</script>

</body>

</html>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 事件(下) 事件对象 在事件对象中记录了很多事件的信息。。。 事件类型 e.type// 事件的类型 例: 按钮...
    新生勿扰阅读 271评论 0 0
  • ECMAscript 基础语法 变量 数据类型 运算符 数组 函数 对象 BOM 浏览器对象模型 window对象...
    浅笑_阅读 232评论 0 0
  • 写在前面: Window和document对象的区别 window对象表示浏览器中打开的窗口 window对象是可...
    给堕落一个理由先阅读 705评论 0 3
  • Window和document对象的区别 window对象window对象表示浏览器中打开的窗口window对象是...
    FConfidence阅读 2,254评论 0 5
  • 十二、JavaScript的DOM特效 在web浏览器上,window对象是一个全局对象,代表web浏览器中一个打...
    刘远舟阅读 383评论 0 1