我正在开发一个小东西,我希望用户能够创建任意数量的小窗口对象,然后像在普通窗口一样在屏幕上独立移动它们。稍后我会尝试制作它,以便你只能抓住窗户的最上面部分。
窗口对象都属于同一类型,WindowObject
,或至少到目前为止一直是这个想法。
我尝试的第一件事就是将功能放在对象本身内部。
HTML
<div id="container">
<div style="width:100px; height:100px; background-color:red">example</div>
<div style="width:100px; height:100px;background-color:red">example</div>
</div>
的JavaScript
var WindowObject = function() {
this.xPos = 0;
this.yPos = 0;
};
WindowObject.prototype.addListeners = function() {
this.test1 = this.mouseDown.bind(this);
this.test2 = this.mouseUp.bind(this);
this.container = document.querySelector("#container");
this.container.addEventListener("mousedown", this.test1, false);
window.addEventListener("mouseup", this.test2, false);
};
WindowObject.prototype.move = function(event) {
event.target.style.position = "absolute";
event.target.style.top = (event.clientY - this.yPos) + "px";
event.target.style.left = (event.clientX - this.xPos) + "px";
};
WindowObject.prototype.mouseUp = function() {
window.removeEventListener("mousemove", this.test3, true);
};
WindowObject.prototype.mouseDown = function(event) {
this.xPos = event.clientX - event.target.offsetLeft;
this.yPos = event.clientY - event.target.offsetTop;
this.test3 = this.move.bind(this);
window.addEventListener("mousemove", this.test3, true);
};
如果您非常缓慢地拖动div(以便鼠标永远不会离开它们),这种方法也有效,并且还要确保不与其他元素重叠。否则,div的位置会搞砸,如果有多个,你可能会发现自己同时拖动了几个div。
我还尝试将功能放在不同类型的对象中,进行一些较小的调整,但结果是一样的。
如果您认为我应该尝试不同的方法,请告诉我。如果没有,我做错了什么?