문제

<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