如何使用香草JS在第二个元素上添加/删除类?

时间:2018-08-23 18:34:48

标签: javascript jquery

我经历了很多堆栈溢出问题,但还没有弄清楚如何做到这一点。我想做的事情很简单,但是我对普通的ole Javascript不好。

愿望

  • 将鼠标悬停在#element1上会将.specialClass添加到#element2
  • 将#element1删除会从#element2中删除.specialClass

如果我能够使用jQuery,这正是我想要完成的任务:

$(document).ready(function() {     
    $('#element1').hover(function(){     
        $('#element2').addClass('specialClass');    
    },     
    function(){    
        $('#element2').removeClass('specialClass');     
    });
});

我在纯Javascript函数中需要相同的功能。我知道这似乎是CSS的工作,但在我的特殊情况下,我需要将它用作JS。

**这个问题不是 Change an element's class with JavaScript的重复,因为这个问题使用的是onClick,而我正在寻找鼠标悬停的位置。 **

2 个答案:

答案 0 :(得分:1)

document.getElementById('element1').addEventListener('mouseover', function(){
  var el = document.getElementById('element2')
  el.classList.add("specialClass");
});

document.getElementById('element1').addEventListener('mouseout', function(){
  var el = document.getElementById('element2')
  el.classList.remove("specialClass");
});
.specialClass {
  color: blue;
}
<div id="element1"> Element 1 </div>

<div id="element2">Element 2</div>

答案 1 :(得分:-1)

虽然您已经有两个答案,但我想我会发布一个替代答案;使用一个命名函数而不是两个匿名函数:

// defining a named function, using arrow syntax:
let toggleClassOnHover = (e) => {

    // here we retrieve the element with the id of 'elementTwo':
    document.getElementById('elementTwo')

      // we use the classList API to work with the classes
      // of that element:
      .classList
      // using the toggle method to add, or remove, the
      // 'hoverClass' class-name to the element, depending
      // on the switch:
      .toggle('hoverClass',
        // if the 'type' property of the Event object ('e')
        // is of the same type and value as 'mouseenter'
        // the switch is (Boolean) true and the class-name is added
        // (if it is not already present); if it is not exactly
        // equal to 'mouseenter' then the switch is false and so the
        // class is removed (if it is already present):
        e.type === 'mouseenter');
  },

  // we're adding two event-listeners to this element so we cache
  // a reference to the element:
  elementOne = document.getElementById('elementOne');

// here we add an event-listener for the 'mouseenter' event,
// binding the named function as the event-handler:
elementOne.addEventListener('mouseenter', toggleClassOnHover);

// here we add an event-listener for the 'mouseleave' event,
// binding the named function as the event-handler:
elementOne.addEventListener('mouseleave', toggleClassOnHover);

let toggleClassOnHover = (e) => {
    document.getElementById('elementTwo').classList.toggle('hoverClass', e.type === 'mouseenter');
  },
  elementOne = document.getElementById('elementOne');

elementOne.addEventListener('mouseenter', toggleClassOnHover);
elementOne.addEventListener('mouseleave', toggleClassOnHover);
div {
  width: 80vw;
  margin: 0.5em auto;
  border: 2px solid currentColor;
  transition: color 0.4s linear;
}

.hoverClass {
  color: limegreen;
}
<div id="elementOne">Element one</div>
<div id="elementTwo">Element two</div>

为什么我使用mouseentermouseleave事件而不是mouseovermouseout事件?在以下演示中对此进行了说明:

function incrementCounts(e) {
  if (event.type === 'mouseover') {
    +this.dataset.mouseovercount++;
  } else if (event.type === 'mouseenter') {
    +this.dataset.mouseentercount++;
  }
}

let elementOne = document.getElementById('elementOne');

elementOne.addEventListener('mouseover', incrementCounts);
elementOne.addEventListener('mouseenter', incrementCounts);
div {
  width: 80vw;
  margin: 0.5em auto;
  border: 2px solid currentColor;
  transition: color 0.4s linear;
}

div p {
  width: 50vw;
  margin: 0.5em auto;
  border: 2px solid #000;
}

#elementOne::before,
#elementOne::after {
  display: inline-block;
  width: 100%;
  border: 1px solid transparent;
  height: 1em;
}

#elementOne::before {
  content: 'Mouseover count: ' attr(data-mouseovercount);
  border-bottom-color: #000;
}

#elementOne::after {
  content: 'Mouseenter count: ' attr(data-mouseentercount);
  border-top-color: #000;
}

.hoverClass {
  color: limegreen;
}
<div id="elementOne" data-mouseovercount="" data-mouseentercount="">
  <p>Element one's content wrapped in a strangely sized &lt;p&gt; element, itself with a <span>&lt;span&gt; descendent.</p></div>
<div id="elementTwo">Element two</div>

最基本的是,mouseover事件在光标进入元素本身的边界以及进入后代元素的边界时触发;而mouseenter仅在光标越过元素本身时触发。

在这种特定情况下,它几乎没有什么区别,但是在其他情况下,mouseover可能会导致意外结果,而mouseenter则更具可预测性。

由于您没有发布自己的HTML,因此我们无法提供有关您的特定问题的详细信息,但是如果第二个元素作为第一个元素的后继兄弟姐妹或后继兄弟姐妹的后代出现在DOM中,则如果只有样式要求,CSS就能提供此功能:

div {
  width: 80vw;
  margin: 0.5em auto;
  border: 2px solid currentColor;
  transition: color 0.4s linear;
}

#elementOne:hover+#elementTwo {
  color: limegreen;
}
<div id="elementOne">Element one</div>
<div id="elementTwo">Element two</div>

参考文献: