====================================================================
看注释理解:
HTML:
<script src="drag.js"> </script>
<script src="limit.js"> </script>
<script>
window.onload=function(){
new drag('div1')创建对象
new limitdrag('div2')
}
</script>
drag.js
function drag(id){
var _this=this
this.disX=0
this.disY=0
this.odiv=document.getElementById(id)
this.odiv.onmousedown=function(){//不是document记得直接再前面加this
_this.fndown()//里面的this要用外层的this
}
return false//不要相互影响
}
drag.prototype.fndown=function(){
var _this=this
var oevent=event
this.disX=oevent.clientX-this.odiv.offsetLeft
this.disY=oevent.clientY-this.odiv.offsetTop
document.onmousemove=function()//函数不能直接在前面加this,要用变量存最外层事件的this,然后再用函数包起来
{
_this.fnmove()//要在函数里面调用
}
document.onmouseup=function()
{
_this.fnup()
}
}
drag.prototype.fnmove=function(){
var oevent=event
this.odiv.style.left=oevent.clientX-this.disX+'px'
this.odiv.style.top=oevent.clientY-this.disY+'px'
}
drag.prototype.fnup=function(){
document.onmousemove=null
}
limit.js
function limitdrag(id){
drag.call(this,id)//继承属性
}
for(var i in drag.prototype)
{
limitdrag.prototype[i]=drag.prototype[i]
}
limitdrag.prototype.fnmove=function(){//方法重写
var oevent=event
var l=oevent.clientX-this.disX
var t=oevent.clientY-this.disY
if(l<0){
l=0
}
if(l>document.documentElement.offsetWidth-this.odiv.offsetWidth)
{
l=document.documentElement.offsetWidth-this.odiv.offsetWidth
}
this.odiv.style.left=l+'px'
this.odiv.style.top=t+'px'
}
====================================================================
系统对象:
本地对象(非静态对象)需要经过实例化new才能用例如Array 、Date
内置对象(静态对象)不能实例化,可以直接使用方法例如Math
宿主对象(由浏览器提供)