gpt4 book ai didi

javascript - onmouseover 事件不适用于 Chrome 中的整个 div

转载 作者:行者123 更新时间:2023-11-28 00:18:14 24 4
gpt4 key购买 nike

我制作了一个 10px div 的网格,并为每个 div 附加了一个鼠标悬停监听器。在 Chrome 中,当我使用鼠标指针从底部输入 div 时,直到我到达 div 的一半时才会触发事件监听器。如果我将 div 做得更大或者使用 Firefox,则不会发生这种情况。为什么 Chrome 中的小 div 会发生这种情况?

<!DOCTYPE html>
<html>
<head>
<script>

window.onload = function() {

for(var row = 0; row < 10; row++) {

var rowDiv = document.createElement("div");
rowDiv.style.lineHeight = 0;

for(var col = 0; col < 10; col++) {

var cellDiv = document.createElement("div");
cellDiv.style.height = "10px";
cellDiv.style.width = "10px";
cellDiv.style.display = "inline-block";
cellDiv.style.backgroundColor = "green";
rowDiv.appendChild(cellDiv);
cellDiv.onmouseover = (function(cell) {
return function() {
cell.style.backgroundColor = "yellow";
};
})(cellDiv);
}
document.getElementById("container").appendChild(rowDiv);
}
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>

最佳答案

将 style.lineHeight 设置为 0 是这里的问题,但这是必要的。不过,有一种方法可以解决它所造成的问题。

首先,我先简单介绍一下原来的情况。我有一个 div 网格,我希望所有相邻的 div 相互接触。我还希望所有 div 上都有单独的鼠标事件监听器。为了使行 div(各个 div 的容器)相互接触,我将它们的行高设置为 0。这产生了不幸的结果,即使鼠标事件监听器仅在每个 div 的上半部分工作(除了底行的那些)。

溢出属性解决了这个问题。只需将每个行 div 的溢出设置为隐藏,鼠标事件监听器将在其 div 的整个区域上工作。

<!DOCTYPE html>
<html>
<head>
<script>

window.onload = function() {

for(var row = 0; row < 10; row++) {

var rowDiv = document.createElement("div");
rowDiv.style.lineHeight = 0;
rowDiv.style.overflow = "hidden";

for(var col = 0; col < 10; col++) {

var cellDiv = document.createElement("div");
cellDiv.style.height = "10px";
cellDiv.style.width = "10px";
cellDiv.style.display = "inline-block";
cellDiv.style.backgroundColor = "green";
rowDiv.appendChild(cellDiv);
cellDiv.onmouseover = (function(cell) {
return function() {
cell.style.backgroundColor = "yellow";
};
})(cellDiv);
}
document.getElementById("container").appendChild(rowDiv);
}
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>

关于javascript - onmouseover 事件不适用于 Chrome 中的整个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30269742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com