有没有一种方法可以将元素悬停并使用纯CSS / JS样式化其他元素?

时间:2019-11-06 19:52:41

标签: javascript html css

当我将鼠标悬停在div上时,我尝试将id赋予要设置样式的元素。而且我为div提供了“ onmouseover”属性,该属性的值可以更改元素的样式,但是即使在我的鼠标不在元素上时,它也会永久更改它

<div class= "container">
      <div class="row"> 
        <div class="item1 col-sm-3" ">
          <a href="#">
            <img class="picture" id="picture1"src="/Rimani/images/logo-tractor-removebg-preview.png">
            <div class="text" onmouseover="hoverStyle()">НОВО ОБОРУДВАНЕ</div>
          </a>
        </div>
           <div class="item2 col-sm-3" onmouseover="hoverStyle()">
          <a href="#" >
            <img class="picture" id="picture2" src="/Rimani/images/logo-tractor-removebg-preview.png">
            <div class="text">НОВО ОБОРУДВАНЕ</div>
          </a>
        </div>
  var hoverElements = document.getElementsByClassName('picture');

function hoverStyle() {
    document.getElementById("picture1").style.filter = "hue-rotate(340deg)"
 document.getElementById("picture2").style.filter = "hue-rotate(340deg)"
}

1 个答案:

答案 0 :(得分:0)

添加一个onmouseout事件:

<div class= "container">
      <div class="row"> 
        <div class="item1 col-sm-3" ">
          <a href="#">
            <img class="picture" id="picture1"src="/Rimani/images/logo-tractor-removebg-preview.png">
            <div class="text" onmouseover="hoverStyle()">НОВО ОБОРУДВАНЕ</div>
          </a>
        </div>
           <div class="item2 col-sm-3" onmouseover="hoverStyle()" onmouseout="unhoverStyle()">
          <a href="#" >
            <img class="picture" id="picture2" src="/Rimani/images/logo-tractor-removebg-preview.png">
            <div class="text">НОВО ОБОРУДВАНЕ</div>
          </a>
        </div>

  var hoverElements = document.getElementsByClassName('picture');

function hoverStyle() {
    document.getElementById("picture1").style.filter = "hue-rotate(340deg)"
 document.getElementById("picture2").style.filter = "hue-rotate(340deg)"
}

  var hoverElements = document.getElementsByClassName('picture');

function unhoverStyle() {
    document.getElementById("picture1").style.filter = "";
 document.getElementById("picture2").style.filter = "";
}