2014-01-25 159 views
-1

我想讓多個元素在懸停時更改顏色。我試圖讓它通過Javascript工作,我不是這個英雄。關於懸停更改多個元素

基本上,我想要實現的是當我將黑色div或白色div切換時,它應該改變顏色(黑色變爲白色,反之亦然)。

的Javascript:

$('#onethirdcolumn').hover(function(){ 
    $('#onethirdcolumn + .leesmeer').css({ 
     'color':'#fff', 
     'background-color':'#000000' 
    }); 
},function(){ 
    $('#onethirdcolumn + .leesmeer').css({ 
     'color':'#000000', 
     'background-color':'#fff' 
    }); 
}); 

jsfiddle

回答

1

這裏有一個FIDDLE

<div class="box w">TEXT</div> 
<div class="box b">TEXT</div> 
<div class="box w">TEXT</div> 
<div class="box b">TEXT</div> 
<div class="box w">TEXT</div> 
<div class="box b">TEXT</div> 


.box { 
    float: left; 
    width: 220px; 
    height: 220px; 
    padding: 10px; 
    border: 1px solid #ddd; 
    transition: all 0.3s linear; 
} 
.box.w { 
    background: white; 
    color: black; 
} 
.box.b { 
    background: black; 
    color: white; 
} 


$(function() { 
    $(document).on('mouseenter','.box', function() { 
    if($('.box').hasClass('w')) { 
     $('.box').toggleClass('b'); 
    } 
    if($('.box').hasClass('b')) { 
     $('.box').toggleClass('w'); 
    } 
    }); 
}); 
4

你不需要使用JavaScript在所有實現這種效果。

假設HTML這樣的:

<div class="wrapper"> 
    <div class="container black"></div> 
    <div class="container white"></div> 
    <div class="container black"></div> 
    <div class="container white"></div> 
</div> 

可以實現在CSS以下懸停效果:

.container { 
    display: inline-block; 
    width: 50px; 
    height: 50px; 
    -moz-transition: all 1s; /* Why? Because they're purdy... */ 
    -webkit-transition: all 1s; 
    transition: all 1s; 
} 
.black { 
    background: #000; 
    color: #fff; /* Yay! Contrast! */ 
} 
.white { 
    background: #fff; 
    color: #000; /* it DOES matter if you're black or white (if you're text, that is) */ 
} 
.black:hover { 
    background: #fff; 
    color: #000; /* if you've got text of the opposite color inside */ 
} 
.white:hover { 
    background: #000; 
    color: #fff; /* and again... */ 
} 

如果你希望他們所有改變:

.wrapper:hover .black { /* Bam! Spice weasel */ 
    background: #fff; 
    color: #000; 
} 
.wrapper:hover .white { 
    background: #000; 
    color: #fff; 
} 

這是Fiddle

+0

那不正是我所期待的。例如,我有一個div(黑色)文本里面(顏色:白色),當懸停div應該變成白色,文字變成黑色。感謝你的努力。 – user3231901

+0

已更新。 +小提琴。 – monners

+0

謝謝,我會嘗試它,如果它能工作,會回覆給你:) – user3231901