【问题标题】:Eventlistener for 'mouseover' and 'mouseleave''mouseover' 和 'mouseleave' 的事件监听器
【发布时间】:2020-09-04 21:47:04
【问题描述】:

我试图让每个单元格在鼠标悬停在它们上方时改变颜色,并在鼠标离开时将其恢复为默认颜色。我只用 HTML 创建了 .container div,而其他 div 是用 JS 循环创建的,所以我发现执行代码很困难。

我很确定我需要将单元格设置为函数外部的变量,但如果是这种情况,我不知道该怎么做。有人可以帮忙吗?

``let container = document.getElementById("container");


function makeRows(rows, cols) {
  container.style.setProperty('--grid-rows', rows);
  container.style.setProperty('--grid-cols', cols);
  for (c = 0; c < (rows * cols); c++) {
    const cell = document.createElement("div");
    cell.innerText = (c + 1);
    container.appendChild(cell).className = "grid-item";
  };
};

makeRows(16, 16);

var gridCells = document.querySelectorAll(".grid-item"); 

gridCells.addEventListener('mouseover', () => {
  gridCells.style.backgroundColor = 'black';
});

gridCells.addEventListener('mouseleave', () => {
  gridCells.style.backgroundColor = '';
});``

【问题讨论】:

    标签: javascript events mouseevent mouseover mouseleave


    【解决方案1】:

    如果您只能使用 javascript,则可以将事件侦听器置于循环中。或者你可以只使用 css .grid-item:hover {background-color: black;}

    let container = document.getElementById("container");
    
    
    function makeRows(rows, cols) {
      container.style.setProperty('--grid-rows', rows);
      container.style.setProperty('--grid-cols', cols);
      for (c = 0; c < (rows * cols); c++) {
        const cell = document.createElement("div");
        cell.innerText = (c + 1);
        container.appendChild(cell).className = "grid-item";
        cell.addEventListener('mouseover', () => {
          cell.style.backgroundColor = 'black';
        });
        cell.addEventListener('mouseleave', () => {
           cell.style.backgroundColor = 'white';
        });
      }
    };
    
    makeRows(16, 16);
    

    【讨论】:

    • 你是个传奇。谢谢,堆。
    • 挑战是使用 Javascript 来操作 HTML DOM,所以我不想使用 CSS。但是,是的,那样肯定会容易得多
    【解决方案2】:

    如果这似乎是一个愚蠢的建议,请原谅我,但为什么不使用 css:hover 属性呢?

    .grid-item:hover {
      background-color: black;
    }
    

    https://www.w3schools.com/cssref/sel_hover.asp

    【讨论】:

    • 嘿,挑战是使用 Javascript 来操作 HTML DOM,所以我不想使用 CSS。但是,是的,那样肯定会容易得多。
    猜你喜欢
    • 1970-01-01
    • 2018-07-19
    • 2014-02-21
    • 1970-01-01
    • 2020-05-06
    • 2020-11-29
    • 2019-12-02
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多