繁体   English   中英

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

[英]onmouseover event doesn't work on whole div in Chrome

我制作了一个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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM