我有一个时间变量,它会更新,并且仅当您将鼠标悬停在另一个元素上时才想重新启动它的值,如果将鼠标悬停在同一元素上,它应该一直更新。我应该如何处理?这是代码的一部分:

// Change shaders
function changeShader() {
  const elements = document.querySelectorAll('.caption');

  elements.forEach(element => {
    element.addEventListener('mouseover', function() {

      if (you hovered on the same element) {
        console.log('you moused over the same element');
      } else {
        console.log('you moused over on a different element');
      }
    });
  });
}

最佳答案

您可以保存上一个悬停的dom并检查是否相同:





function changeShader() {
  let last_hover;
  const elements = document.querySelectorAll('.caption');

  elements.forEach(element => {
    element.addEventListener('mouseover', function() {
      if (last_hover == this) {
        console.log('you moused over the same element');
      } else {
        console.log('you moused over on a different element');
      }
      last_hover = this;
    });
  });
}

changeShader()

.caption, .no-hover{
  padding:10px;
  margin-bottom: 25px;
  background-color: #ccc;
  cursor: pointer;
}

<div class="caption">I am Caption 1</div>
<div class="caption">I am Caption 2</div>
<div class="caption">I am Caption 3</div>
<div class="caption">I am Caption 4</div>
<div class="caption">I am Caption 5</div>

08-07 09:50