简体   繁体   中英

Javascript: Hover element, change class in unrelated element

I've searched far and wide, and cannot find a solution.

I have two divs. One to the right of the other. In each div, I have list elements, but they are in no way parents or siblings, so I cannot use CSS.

Does anyone have a solution, where I can have a link anywhere in my html document, that when hovered, changes the class of another element, regardless of where in the html document it is placed? Javascript for example.

The idea is that when I hover an element in the left list, it will highlight the element in the right list that is considered related to it.

There are many ways to achieve this. I've created an example that uses jQuery to manipulate the class on another element for the mouseenter mouseleave events (basically hover ).

<div class="red">
  x
</div>
<div class="green">
  y
</div>

$('.red').on('mouseenter mouseleave', function() {
    if ($('.green').hasClass('hover')) {
    $('.green').removeClass('hover');
  } else {
    $('.green').addClass('hover');
  }
});

Sample

Jquery is a fairly large library. I highly suggest you do this in pure javascript if you aren't using Jquery anywhere else in your webpage. Here is an example I created that changes the class of one div when another is hovered with a simple If statement.

https://jsfiddle.net/c16rvt0y/1/

function highlightDiv(){
    if (document.getElementById("highlightMe").className === "otherDiv"){
       document.getElementById("highlightMe").className = "otherDiv otherDivHighlighted"
  } else {
     document.getElementById("highlightMe").className = "otherDiv"
  }
}

Here is an example that targets separate divs depanding on which one is called by the function:

https://jsfiddle.net/c16rvt0y/2/

function highlightDiv(highlightMeID){
    if (document.getElementById(highlightMeID).className === "otherDiv"){
       document.getElementById(highlightMeID).className = "otherDiv otherDivHighlighted"
  } else {
     document.getElementById(highlightMeID).className = "otherDiv"
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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