javascript
拖拽元素自定义html模板,JS实现的自定义网页拖动类
本文實例講述了JS實現的自定義網頁拖動類。分享給大家供大家參考,具體如下:
先來看運行效果截圖如下:
在線演示地址如下:
具體代碼如下:
/p>
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
自寫的拖動類……var d=document;//給document對象一個通用的事件偵聽方法
d.addListener=function(e,f,b){
this.attachEvent?this.attachEvent('on'+e,f):this.addEventListener(e,f,b);
}
d.removeListener=function(e,f,b){
this.detachEvent?this.detachEvent('on'+e,f):this.removeEventListener(e,f,b);
}
function $(){//接收一個id參數,返回帶有startDrag方法的對象
var o=document.getElementById(arguments[0]);
o.addListener=function(e,f,b){
this.attachEvent?this.attachEvent('on'+e,f):this.addEventListener(e,f,b);
}
o.removeListener=function(e,f,b){
this.detachEvent?this.detachEvent('on'+e,f):this.removeEventListener(e,f,b);
}
o.startDrag=function(obj){//參數obj默認為o本身,可以傳其它參數以確定要移動的對象
var obj=obj?obj:o;
var sx,sy;
o.style.cursor="move";
o.addListener("mousedown",function(e){
e||event;
if(e.button==1||e.button==0){
sx=e.clientX-obj.offsetLeft;sy=e.clientY-obj.offsetTop;
d.addListener("mousemove",move,false);
d.addListener("mouseup",stopDrag,false);
}
},false);
var stopDrag=function(){
d.removeListener("mousemove",move,false);
d.removeListener("mouseup",stopDrag,false);
}
var move=function(e){
e||event;
window.getSelection ? window.getSelection().removeAllRanges() :
document.selection.empty();
if(e.preventDefault)e.preventDefault();//這兩句便是解決firefox拖動問題的.
with (obj.style){
position="absolute"
left=e.clientX-sx+"px";
top=e.clientY-sy+"px";
}
}
}
return o;
}
window.οnlοad=function(){$("ok").startDrag($("os"))}//本例中拖動ok元素,移動其父元素
*{margin:0;padding:0}
#ok{width:215px;height:170px;background:url(images/sample1.gif)}
#os{width:400px;height:300px;background:#09f;left:300px}
#os2{width:400px;height:300px;background:#f90;}
希望本文所述對大家JavaScript程序設計有所幫助。
總結
以上是生活随笔為你收集整理的拖拽元素自定义html模板,JS实现的自定义网页拖动类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 企业年金辞职时可以提取吗 有哪些提取的条
- 下一篇: 几成仓位是什么意思