<!DOCTYPE html>
<html lang="en">
<!--
系统对象
1,本地对象(非静态对象)
什么是本地对象
常用的: Object Function Array String Boolean Number Date
2,内置对象(静态对象)
Global对象 只是一个概念
Math 对象
不能new出来用 不需要经过实例化
3,宿主对象
js的运行环境 DOM BOM
或者是node.js
本地对象 和 内置对象 和js的运行环境无关 是js语言本省所具备的
-->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#div1 {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
}
#div2 {
width: 200px;
height: 200px;
background-color: yellow;
position: absolute;
top:300px;
}
</style>
<script>
window.onload=function(){
new Drag('div1');
new LimitDrag('div2');
}
var oDiv = null;
var x = 0;
var y = 0;
function Drag(id) {
var _this=this;
// var oDiv = null;
this.x = 0;
this.y = 0;
this.oDiv = document.getElementById(id);
this.oDiv.onmousedown = function(ev){
_this.fnDown(ev);
return false;
}
}
Drag.prototype.fnDown = function (ev) {
var _this=this;
var e = ev || event;
this.x = e.clientX - this.oDiv.offsetLeft;
this.y = e.clientY - this.oDiv.offsetTop;
document.onmouseover = function(ev){
_this.fnMove(ev);
};
document.onmouseup = function(ev){
_this.fnUp()
};
}
Drag.prototype.fnMove=function(ev) {
var e = ev || event;
this.oDiv.style.left = e.clientX - this.x + 'px';
this.oDiv.style.top = e.clientY - this.y + 'px';
}
Drag.prototype.fnUp=function fnUp() {
document.onmouseover = null;
document.onmouseup = null;
}
// 继承
function LimitDrag(id){
Drag.call(this,id); //继承属性
}
for(var i in Drag.prototype){
LimitDrag.prototype[i]=Drag.prototype[i];
}
LimitDrag.prototype.fnMove=function(ev){
var e = ev || event;
var l=e.clientX - this.x ;
var t=e.clientY - this.y ;
this.oDiv.style.left = l + 'px';
this.oDiv.style.top = t + 'px';
if(l<0){
l=0;
}
else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth){
l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
}
}
</script>
</head>
<body>
<div id="div1">普通拖拽</div>
<div id="div2">限制范围的拖拽 </div>
</body>
</html>
用面向对象 写拖拽功能 和javascript的继承写限制拖拽
最新推荐文章于 2021-11-13 11:51:07 发布