实现思路:
(1)首先改变被拖动元素的布局属性为“position:absolute”,其父框为“position:relative”;
(2)捕捉鼠标事件“mousedown”、“mousemove”、“mouseup”;
(3)当触发“mousedown”时,记录下当前鼠标在元素中的相对位置,_x,_y;
(4)紧接着处理“mousemove”事件,通过改变元素的top和left属性来移动元素;
(5)当触发“mouse”事件时,终止拖动。
<!DOCTYPE html>
<html>
<head>
<title>原生js实现拖拽</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style type="text/css">
#div1{
width: 100px; height: 100px;
background-color: #4D4D4D;
position: absolute; cursor: pointer;

本文介绍了如何使用原生JavaScript实现div元素的拖拽效果。主要步骤包括将div的布局属性设置为absolute,监听鼠标事件,记录鼠标在元素内的初始位置,并在mousemove事件中更新元素的top和left属性来移动元素。同时,注意到在不同浏览器中获取鼠标位置的方法差异。

1039

被折叠的 条评论
为什么被折叠?



