当前位置: 首页 > news >正文

按下鼠标进行拖拽,让元素跟随鼠标进行移动,鼠标抬起,元素停止移;js鼠标拖拽 (鼠标按下事件:onmousedown、鼠标移动事件:onmousemove、鼠标抬起事件:onmouseup)

需求如下:

按下鼠标进行拖拽,让元素跟随鼠标进行移动,鼠标抬起,元素停止移动。

解析:

鼠标按下事件:onmousedown

鼠标移动事件:onmousemove

鼠标抬起事件:onmouseup

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#chatFrame{width: 300px;height: 300px;position: absolute;}</style>
</head>
<body><div id="chatFrame" style="width: 300px;height: 300px;background-color: yellowgreen;"></div><script>var div = document.getElementById("chatFrame");var isDragging = false; // 用于标识是否正在拖拽// 鼠标按下事件div.onmousedown = function(event) {isDragging = false; // 每次鼠标按下时重置拖拽标识if (div.setCapture !== undefined) {div.setCapture();}var disX = event.clientX - div.offsetLeft;var disY = event.clientY - div.offsetTop;// 鼠标移动事件document.onmousemove = function(event) {isDragging = true; // 如果发生了移动,认为发生了拖拽var x = event.clientX - disX;var y = event.clientY - disY;div.style.left = x + 'px';div.style.top = y + 'px';};// 鼠标抬起事件document.onmouseup = function() {if (div.releaseCapture !== undefined) {div.releaseCapture();}document.onmousemove = null;// 如果没有发生拖拽,则执行点击事件的默认行为if (!isDragging) {handleIm();}};return false; // 阻止默认行为};// 鼠标点击事件处理函数function handleIm() {console.log("Handle click event");// 在这里添加你希望执行的点击事件的逻辑}</script>
</body>
</html>
http://www.lryc.cn/news/347816.html

相关文章:

  • 第十二章 项目采购管理
  • PSFR-GAN复现
  • 函数和数组
  • docker安装时报错:Error: Nothing to do
  • 白盒测试:覆盖测试及测试用例设计
  • Java高级开发2024高频面试提问题目
  • Kamailio openssl 3.0.x 需要注意的事项
  • SpringAMQP Work Queue 工作队列
  • 一分钟带你了解什么是等保测评
  • 宝塔面板怎么解决nginx跨域问题
  • Python 自动化脚本系列:第1集
  • 基于PHP开发的图片高清无损在线压缩源码系统 带完整源代码以及搭建教程
  • Linux提权--SUDO(CVE-2021-3156)Polkit(CVE-2021-4034)
  • nodejs里面的 http 模块介绍和使用
  • MVC框架简易实现【精细】
  • Java入门基础学习笔记18——赋值运算符
  • csv 可视化 python代码
  • HashMap 和 Hashtable区别的底层原理
  • 代码随想录35期Day32-Java
  • ROS 2边学边练(45)-- 构建一个能动的机器人模型
  • 【第66例】IPD体系进阶:华为IPD发展历程
  • websevere服务器从零搭建到上线(四)|muduo网络库的基本原理和使用
  • C语言笔记10
  • BMS-HiL主要功能
  • idea无法识别加载pom.xml文件
  • C语言笔记12
  • 说一下 hibernate 的缓存机制?
  • Mac安装jadx
  • 风扇开启执行逻辑
  • 调用函数实现数组的输入排序插入与输出