js:簡單的拖動效果
html:
movebox
css
#boxmove{ position: absolute; width: 200px; border:1px solid #ccc; height: 200px; color: red; background-color: blue; text-align: center; font-size: 30px; }
js
var o, //捕獲到的事件 X, //boxmove水平寬度 Y; //boxmove垂直高度function getObject(obj,e){ //擷取捕獲到的對象 o = obj; // document.all(IE)使用setCapture方法綁定;其餘比如FF使用
//Window對象針對事件的捕捉 document.all?o.setCapture() : window.captureEvents(Event.MOUSEMOVE); X = e.clientX - parseInt(o.style.left); //擷取寬度, Y = e.clientY - parseInt(o.style.top); //擷取高度,}document.getElementById(boxmove).onmousedown = function(e){
//boxmove捕獲事件並處理 e-->FF window.event-->IE
getObject(this,e||event); };document.onmousemove = function(dis){ //滑鼠移動事件處理 if(!o){ return; } if(!dis){ //事件 dis = event ; }
//設定boxmovebox樣式隨滑鼠移動而改變
o.style.left = dis.clientX - X +px;
o.style.top = dis.clientY - Y + px;};
document.onmouseup = function(){
//滑鼠鬆開事件處理
if(!o){ return; }
// document.all(IE)使用releaseCapture解除綁定;
//其餘比如FF使用window對象針對事件的捕捉
document.all?o.releaseCapture() : window.captureEvents(
Event.MOUSEMOVE|Event.MOUSEUP) o = ''; //還Null 物件};
需要注意的是,因為需要更改div的left和top。這兩個屬性需要以內聯方式給出,否則不行。