<body>
<div class = "div0">1</div>
<div class = "div1">2</div>
<button>按钮</button>
<script>
var div0 = document.querySelector(".div0");
var div1 = document.querySelector(".div1");
div0.setBg = function(){
this.style.width="50px";
this.style.height = "50px";
this.style.border = "1px solid #000000";
this.style.backgroundColor = "red";
}
HTMLDivElement.prototype.setBg = function(){
this.style.width = "50px";
this.style.height = "50px";
this.style.border = "1px solid #000000";
this.style.backgroundColor = "red";
}
div0.setBg();
div1.setBg();
Object.defineProperties(HTMLDivElement.prototype,{
_drag:{
writable:true,
value:false,
},
width:{
set:function(_v){
this.style.width = _v.toString().indexOf("px")>-1 ?_v : _v+"px";
},
get:function(){
return parseFloat(getComputedStyle(this).width);
}
},
height:{
set:function(_v){
this.style.height = _v.toString().indexOf("px")>-1 ? _v : _v+"px";
},
get:function(){
return parseFloat(getComputedStyle(this).height);
}
},
bgColor:{
set:function(_v){
this.style.backgroundColor = (typeof _v === "string") ? _v : "#"+_v.toString(16).padstart(6,"0");
},
get:function(){
return parseFloat(getComputedStyle(this).backgroundColor);
}
},
drag:{
set:function(_v){
this._drag = _v;
if(_v){
this.style.position = "absolute";
return this.addEventListener("mousedown",this.dragHandler);
}
this.removeEventListener("mousedown",this.dragHandler);
},
get:function(){
return this._drag;
}
},
dragHandler:{
value:function(e){
if(e.type === "mousedown"){
e.preventDefault();
document.target = this;
document.offset = {x:e.offsetX,y:e.offsetY};
document.addEventListener("mousemove",this.dragHandler);
document.addEventListener("mouseup",this.dragHandler);
}else if(e.type === "mousemove"){
this.target.style.left=e.clientX-this.offset.x+"px";
this.target.style.top=e.clientY-this.offset.y+"px";
}else if(e.type === "mouseup"){
document.removeEventListener("mousemove",this.target.dragHandler);
document.removeEventListener("mouseup",this.target.dragHandler);
}
}
}
})
div0.width = 100;
div0.height = 100;
div0.bgColor = "red";
div1.width = 50;
div1.height = 50;
div1.bgColor = "cyan";
bn = document.querySelector("button");
bn.addEventListener("click",clickHandler);
function clickHandler(e){
div0.drag = !div0.drag;
div1.drag = !div1.drag;
}
</script>
</body>
点击按钮移动方块,再次点击禁止移动
最新推荐文章于 2024-09-25 14:00:00 发布