如何更改:当一个元素悬停在一个元素上时,元素上的悬停状态?

时间:2014-03-01 22:01:12

标签: javascript css pseudo-element

<img>
<button>

button:hover
  color: blue

我想要按钮的:当img悬停时,悬停效果会发生。这可以在CSS中完成吗?如果没有,JS中最简单的方法是什么(jQuery很好)?

3 个答案:

答案 0 :(得分:2)

如果此元素具有相同的父元素,则可以使用“+”或“〜”CSS选择器

img:hover + button{color:red}

http://jsfiddle.net/K4U9p/

答案 1 :(得分:1)

如果元素没有相同的父元素,则可以在jQuery中使用:

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

删除事件处理程序:

$img.off('mouseenter mouseleave');

答案 2 :(得分:1)

如果你想使用(纯)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 = "";
}

或者您可以使用单一功能

img.onmouseout = modifyButton;

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

小提琴:Two func. Single Func.

相关问题