鼠标拖拽效果

此为鼠标拖拽效果,多用于放大视图 用js展示出来
示图:


image.png

<!DOCTYPE html>
<html lang="zh">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
width: 300px;
height: 400px;
background-color: bisque;
position: absolute;

    }
</style>

</head>

<body>
<div id="box"></div>
<script>
//获取标签
let box = document.getElementById("box")
//当鼠标松开时div的位置
box.onmousedown = function (e) {
let ox = e.offsetX
let oy = e.offsetY
//浏览器窗口
document.onmousemove = function (e2) {
let cx = e2.clientX
let cy = e2.clientY
let _left = cx - ox
let _top = cy - oy
//浏览器不能移出左边框
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
}
box.style.left = _left + "px"
box.style.top = _top + "px"
}

}
    document.onmouseup = function () {
        document.onmousemove = null
    }
</script>

</body>

</html>

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

推荐阅读更多精彩内容

  • <!DOCTYPE html> Document .box{width: 300px;height: ...
    b8a282f5d556阅读 514评论 0 0
  • 本次编写结果 代码展示:<!DOCTYPE html> Document #box {position: abs...
    风流_8cce阅读 1,105评论 0 0
  • ECMAscript 基础语法 变量 数据类型 运算符 数组 函数 对象 BOM 浏览器对象模型 window对象...
    浅笑_阅读 1,631评论 0 0
  • #前端基础 # ## JavaScript基础 ## ###渲染机制与变量 ### script代码为什么放到bo...
    hmg阅读 2,224评论 1 1
  • (1)前端基础面试题 一、HTML 面试题 1、html 语义化? 阅读代码时能根据标签理解你的用意,便于阅读 方...
    Coder__T阅读 3,593评论 0 5