How do I change :hover status on an element when a different element is hovered over?

StackOverflow https://stackoverflow.com/questions/22120941

  •  18-10-2022
  •  | 
  •  

Вопрос

<img>
<button>

button:hover
  color: blue

I want the button's :hover effect to happen when the img is hovered over. Can this be done in CSS? If not, what's the simplest way in JS (jQuery is fine)?

Это было полезно?

Решение

If this elements have same parent, you can use "+" or "~" CSS selector

img:hover + button{color:red}

http://jsfiddle.net/K4U9p/

Другие советы

If the elements don't have the same parent, you could use, in jQuery:

$img.hover(function() { //mouse enter
    $button.addClass('hover');
}, function() { //mouse leave
    $button.removeClass('hover');
});

To remove the event handler:

$img.off('mouseenter mouseleave');

If you want to use (pure) JS

var button  = document.getElementById("button");
var img     = document.getElementById("img");

img.onmouseover = modifyButton;
img.onmouseout  = resetButton;

function modifyButton() {
    button.style.color = "red";
}

function resetButton() {
    button.style.color = "";
}

or you could use a single function

img.onmouseout = modifyButton;

function modifyButton() {
    if (button.style.color != "red") {
        button.style.color = "red"
    } else {
        button.style.color = "";
    }
}

Fiddles: Two func. Single Func.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top