下面是一些使用 JavaScript 创建一堆 div 元素来充当像素的代码。我为 mouseover 事件添加了一个事件侦听器,并检查鼠标是否被按下。如果按下鼠标,我会更改该像素的颜色。最终结果是一个简单的绘图函数。
我相信使用 HTML5 canvas 之类的东西会更有效,但我只是在玩弄 DOM 以及事件的工作原理。
我面临的问题是,Chrome 浏览器经常认为我正在尝试拖动主体或 div,并且不再触发鼠标悬停事件。这似乎是一个不寻常的问题,我想知道是否有人知道如何避免它。
var numOfPxls = 0;
var resolution = "13px"
while (numOfPxls < 1300) {
const pxl = document.createElement("div");
pxl.classList.add("pxl");
pxl.style.cssText = `
height: ${resolution};
width: ${resolution};
`;
document.querySelector("body").appendChild(pxl);
pxl.addEventListener("mouseover", function(e){
// only continue if left click
if (e.buttons != 1) return;
this.style.backgroundColor = "pink";
});
numOfPxls++;
}
body {
margin: 0;
background-color: black;
}
.pxl {
display: inline-block;
background-color: black;
}
<body>
</body>
万一以后有人偶然发现这个问题,我就发现了这个问题。
“mousedown”事件的默认操作是启动拖动。 div 元素无法拖动。要解决此问题,请使用事件的 PreventDefault 方法。
i.e.
add onto
...
pxl.addEventListener("mouseover", function(e){
// only continue if left click
if (e.buttons != 1) return;
this.style.backgroundColor = "pink";
});
...
with:
...
pxl.addEventListener("mouseover", function(e){
// only continue if left click
if (e.buttons != 1) return;
this.style.backgroundColor = "pink";
});
//new line to prevent drag default on mousedown
pxl.addEventListener("mousedown", e => e.preventDefault());
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)