好的,看起来应该很简单。我需要使用一个已经存在的 div 并根据鼠标在窗口中的位置移动它。我到处搜索,这让我找到了做同样事情的过于复杂的方法,并且涉及到 j-query 的使用。我需要严格使用 javascript 来做我想做的事情。
方法 :
var mousePosition;
var div;
(function createDiv(){
div = document.createElement("div");
div.style.position = "absolute";
div.style.left = "0px";
div.style.top = "0px";
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "blue";
div.addEventListener('mousedown', handleKeyPressed, true);
document.body.appendChild(div);
})();
function handleKeyPressed(event) {
event.preventDefault();
mousePosition = {
x : event.clientX,
y : event.clientY
};
div.style.left = mousePosition.x;
div.style.top = mousePosition.y;
//alert("whoa!");
}
原文由 StoneAgeCoder 发布,翻译遵循 CC BY-SA 4.0 许可协议
我想你正在寻找更像这样的东西
小提琴