JavaScript实现简单的拖动效果
拖动是一件非常酷的事情。你点击某个对象,并按住鼠标不放,将鼠标移动到另一个区域,然后释放鼠标按钮将对象放在这里。
下面是一个简单的案例:
HTML部分:注意,拖动元素一定要为绝对定义,即position = absolute;
代码如下:
<div style="position:absolute;height:100px;width:100px;background:red" class="draggable"></div> <script src="dome.js"></script>
JS部分(dome.js):
var EventUtil = { // 获取事件和目标 getEvent : function (event) { return event ? event : window.event; }, getTarget : function (event) { return event.target || event.srcElement; }, // 添加监听事件 addEvent : function (element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + type, handler); } }, // 注销监听事件 delEvent : function (element, type, handler) { if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else if (element.detachEvent) { element.detachEvent("on" + type, handler); } } } var DragDrop = function () { // 判断DOM元素是否正在被拖动的标志 var dragging = null; // DOM元素左上角与鼠标指针的差值 diffX = 0; diffY = 0; function handleEvent(event) { event = EventUtil.getEvent(event); var target = EventUtil.getTarget(event); switch (event.type) { case "mousedown" : // 判断DOM元素的class中是否含有draggable属性 if (target.className.indexOf("draggable") > -1) { dragging = target; diffX = event.clientX - target.offsetLeft; diffY = event.clientY - target.offsetTop; } break; case "mousemove" : if (dragging != null) { target.style.left = event.clientX - diffX + "px"; target.style.top = event.clientY - diffY + "px"; } break; case "mouseup" : dragging = null; break; } } return { enable : function () { EventUtil.addEvent(document, "mousedown", handleEvent); EventUtil.addEvent(document, "mousemove", handleEvent); EventUtil.addEvent(document, "mouseup", handleEvent); }, disable : function () { EventUtil.delEvent(document, "mousedown", handleEvent); EventUtil.delEvent(document, "mousemove", handleEvent); EventUtil.delEvent(document, "mouseup", handleEvent); } } }(); DragDrop.enable();
这里需要讲解的是diffX和diffY,它们表示元素左上角与鼠标指针的差值。
diffX = 鼠标的x坐标 - 元素对象的offsetLeft
diffY = 鼠标的y坐标 - 元素对象的offsetTop
以上就是本文的全部内容,希望对大家的学习有所帮助。
相关推荐
EdwardSiCong 2020-11-23
yungpheng 2020-10-19
jipengx 2020-11-12
橄榄 2020-11-03
lyqdanang 2020-11-02
wservices 2020-10-30
onepiecedn 2020-10-29
数据人 2020-10-26
dfphoto 2020-10-16
hackerlpy 2020-09-07
tianyayi 2020-08-16
Dullonjiang 2020-08-15
fengling 2020-08-15
wordmhg 2020-08-06
guotiaotiao 2020-08-06
zhangsyi 2020-07-28
千锋 2020-07-27
ahnjwj 2020-07-28