简单的鼠标可拖动div 兼容IE/FF_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:47:44
Original
1228 people have browsed it

一个简单的可拖动div,随着鼠标的移动,div可随之走动

 

主要思路:

一个div,注册监听onmousedown事件,然后处理获取的对象及其相关值(对象高度,clientX/clientY位置等)

并继而转为监测onmousemove事件,在鼠标移动事件中更新div对象的位置属性

鼠标松开的时候解除监听,更新位置完成。

 

需要注意的两点

1.更新对象的位置需要用到o.style.left等,这些CSS属性只能内嵌才能被访问到:

<div id="box" style="left:200px;top:200px;"> box </div>
Copy after login

放在中是无法访问的,比如:

#box{position: absolute;left:200px;top:200px;width: 200px;}
Copy after login

假如这样做,显示的是无法获取值,请看举例:

//    alert(e.clientX+"  -- " + o.style.left+" -- "+ X);
Copy after login

这样的结果为 :(详情看后边代码)

2. FireFox中是不能直接取event对象的,一般我们都会简单地使用 e = e || event 来区分,其中e是相应于FF中函数的参数部分

比如:

 document.getElementById("box").onmousedown = function(e){         getObject(this,e||event);       //box捕获事件并处理  e-->FF  window.event-->IE    };
Copy after login

当然有些时候也可以这样考虑:使用全局对象arguments[0]来替代捕获到的事件参数

//    dis = arguments[0]||window.event;   //如果上面那句在FF下无法获取事件,听说可以通过 arguments[0]获取FF下的事件对象
Copy after login

对于拖拽事件这里使用到了另外一种常用的方法:

// document.all(IE)使用setCapture方法绑定;其余比如FF使用Window对象针对事件的捕捉        document.all?o.setCapture() : window.captureEvents(Event.MOUSEMOVE);  // document.all(IE)使用releaseCapture解除绑定;其余比如FF使用window对象针对事件的捕捉        document.all?o.releaseCapture() : window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP)
Copy after login

最后是一个可随鼠标拖动的div

代码,有注释,希望能理解:

Examples    
<div id="box" style="left:200px;top:200px;"> box </div>
Copy after login

 

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!