纯JS(JavaScript)实现拖拽效果,兼容各大浏览器

来源:互联网 发布:淘宝企业店铺能转让吗 编辑:程序博客网 时间:2024/06/04 18:17

为了让每一个看了这篇博客的人都会拖拽效果,我会以最简单最有条理的为大家讲清楚。

首先大致讲解一下拖拽的实现思路

  1. 确定拖拽对象,就是需要拖拽的元素,我们给它一个id或一个class作为唯一标识

  2. 拖拽过程用到三个时间,鼠标按下事件,鼠标移动事件,鼠标抬起事件。

一定要养成先理清思路再具体实现的习惯,上面的思路列出来就感觉很简单了吧。

第一步,确定拖拽对象,这里我写了一个div

<div id="div1">//给出唯一标识</div>

css简单设置一下样式:

* {        margin: 0;        padding: 0;   }#div1 {        position: absolute;        width: 100px;        height: 100px;        cursor: move;        background-color: red;    }

第二步,事件处理

这里涉及到三个事件,我都说明一下,知道的就直接跳过吧

鼠标按下事件:onmousedown事件会在鼠标按键被按下时发生object.onmousedown=function(){//object为获取的元素    SomeJavaScriptCode//你要执行的代码};鼠标移动事件:onmousemove事件会在鼠标指针移到指定的对象时发生object.onmousemove=function(){//object为获取的元素    SomeJavaScriptCode//你要执行的代码};鼠标抬起事件:onmouseup 事件会在鼠标按键被松开时发生object.onmouseup=function(){//object为获取的元素    SomeJavaScriptCode//你要执行的代码};

三个事件用法都相同,知道了这几个事件就开始实现我们的功能吧

window.onload = function () {    var div1 = document.getElementById("div1");//获取拖动元素    div1.onmousedown = function (evt) {//鼠标按下事件        var oEvent = evt || event;        var distanceX = oEvent.clientX - div1.offsetLeft;//clientX表示鼠标指针的坐标        var distanceY = oEvent.clientY - div1.offsetTop;//offsetTop获取元素距离上面的位置,返回的是数字        document.onmousemove = function (evt) {//鼠标移动事件            var oEvent = evt || event;            var left = oEvent.clientX - distanceX;//获取拖动是元素的位置            var top = oEvent.clientY - distanceY;            if (left <= 0) {//防止越过浏览器左边缘                left = 0;            }            else if (left >= document.documentElement.clientWidth - div1.offsetWidth) {//防止越过右边缘                left = document.documentElement.clientWidth - div1.offsetWidth;            }            if (top <= 0) {                top = 0;            }            else if (top >= document.documentElement.clientHeight - div1.offsetHeight) {                top = document.documentElement.clientHeight - div1.offsetHeight;            }            div1.style.top = top + "px";//重新设置元素位置            div1.style.left = left + "px";        }        div1.onmouseup = function () {//鼠标抬起事件            document.onmousemove = null;//清除鼠标按下事件            div1.onmouseup = null;        }    }}

以上所有内容不依赖任何插件,纯HTML、css、js实现,复制即可使用,所有浏览器均兼容。欢迎评论留言。

阅读全文
0 0
原创粉丝点击