在css中将孩子悬停时更改父div的背景颜色?

时间:2013-10-28 23:22:37

标签: javascript css colors hover

我正在进行网页设计任务,到目前为止,我对大多数css样式感到相当不舒服,此任务涉及div中的3个彩色框。当盒子悬停时,我必须将此div的白色背景变成相同颜色的盒子。

HTML:

            <div id="t1_color_one" class="t1_colors" style="background: goldenrod;"></div>
            <div id="t1_color_two" class="t1_colors" style="background: lightgreen;"></div>
            <div id="t1_color_three" class="t1_colors" style="background: palevioletred;"></div>

不要试图成为那个提出愚蠢问题的“那个人”......但我根本不知道如何处理这个问题。感谢您的任何提示,非常感谢

3 个答案:

答案 0 :(得分:1)

这是工作示例,这是你想要的&gt;&gt; http://jsfiddle.net/mbTBu/

$(document).ready(function(){
  $(".t1_colors").hover(function(){
    var $c=$(this).css("background-color");
        $("#task1").css('background-color', $c);
  });
});

你也可以使用,mouseover&amp; mouseout功能可以恢复颜色。 http://jsfiddle.net/mbTBu/2/

答案 1 :(得分:1)

我认为Jeremy意味着外部div id =“task1”必须假设div内部悬停的颜色,所以解决方案是使用javascript:

$('.t1_colors').hover(function(){
   $('#task1').css('background-color', $(this).css('background-color'));
},
 function(){
   $('#task1').css('background-color', white);
 }
);

答案 2 :(得分:0)

以下是纯javascript中的答案

window.addEventListener('load', function(event)
{
    var divs = document.getElementsByClassName('t1_colors');
    var count_of_divs = divs.length;

    for(var i = 0; i<count_of_divs; i++)
    {
        divs[i].addEventListener('mouseover', function(e)
        {
            document.getElementById('task1').setAttribute('style', e.target.getAttribute('style'));
        }, false);

        divs[i].addEventListener('mouseout', function(e)
        {
            document.getElementById('task1').removeAttribute('style');
        }, false)
    }
}, false);

你可以在jsFiddle link中查看它。