2025-03-28

···<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>事件</title>
<style>
#box {
width: 400px;
height: 200px;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
let box = document.getElementById("box");

    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;

            
            let docWidth = document.documentElement.clientWidth;
            let docHeight = document.documentElement.clientHeight;

            
            if (_left < 0) {
                _left = 0;
            }
           
            if (_left > docWidth - box.offsetWidth) {
                _left = docWidth - box.offsetWidth;
            }
           
            if (_top < 0) {
                _top = 0;
            }
            
            if (_top > docHeight - box.offsetHeight) {
                _top = docHeight - box.offsetHeight;
            }

            box.style.left = _left + "px";
            box.style.top = _top + "px";
        };
    };
    document.onmouseup = function() {
        document.onmousemove = null;
    };
</script>

</body>
</html>

效果展示

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

相关阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 28,894评论 1 45
  • 什么是jQuery? jQuery是一个快速的、轻量的、功能丰富的js库。 jQuery的官网 http://jq...
    小五同学H阅读 310评论 0 0
  • 十三.事件和捕获<!DOCTYPE html> #box1{width: 400px;height: 4...
    学python的铁头娃阅读 377评论 0 0
  • 技术交流QQ群:1027579432,欢迎你的加入! 欢迎关注我的微信公众号:CurryCoder的程序人生 1....
    CurryCoder阅读 417评论 0 1
  • 1 放大镜实例 页面结构:创建左右两个容器,左边容器中添加一张图片背景图,右边容器中添加一张与背景图成比例放大的图...
    果木山阅读 343评论 0 0

友情链接更多精彩内容