<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