HW06-鼠标拖曳

作业分析

本次使用div+css+Javascrip等标签编写出如下的效果:

JS实现鼠标拖曳最终演示图:


image.png

代码展示入下(使用vscode编辑)

html代码展示如下:

<!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: 200px;
            background-color: red;
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="box">
        <h2>拖拽</h2>
    </div>
    <script>
        // 获得要操作的标签对象
        let box = document.getElementById('box')
        // 事件1:鼠标位置1 按下,获得offsetX和offsetY
        box.onmousedown = function (e) {
            let ox = e.offsetX
            let oy = e.offsetY
            // 事件2:鼠标在网页中移动(包含在事件1中)
            document.onmousemove = function (e2) {
                let cx = e2.clientX
                let cy = e2.clientY
                // 计算left和top
                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"
            }
        }
        // 事件3:鼠标位置2 抬起,停止移动
        document.onmouseup = function () {
            // 停止移动
            document.onmousemove = null
        }
    </script>
</body>

</html>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 作业分析 本次使用div+css等标签编写出如下的效果: 管理员登陆页面网页最终演示图: 代码展示入下(使用vsc...
    Ace_656e阅读 43评论 0 0
  • Emmet和结构伪类 认识emmet语法 ◼ Emmet (前身为 Zen Coding) 是一个能大幅度****...
    二斤寂寞阅读 2,844评论 0 0
  • 1 爬虫高级 1.1 动态HTML处理和机器图像识别 爬虫(Spider),反爬虫(Anti-Spider),反反...
    创造new_world阅读 3,146评论 0 0
  • 学习目标: 了解html的基本结构 掌握标题标签: 掌握段落标签: 掌握通用块标签: 掌握图片标签: 掌握超链接标...
    husky_1阅读 7,332评论 0 12
  • 自学前端也有小半年了,从最开始的一脸懵逼到现在的勉强入门。想来,也该好好总结一下了。 前端开发初识 1、[编辑器的...
    fuheideMayuyu阅读 3,251评论 0 1

友情链接更多精彩内容