2017-07-23 143 views
2

當鼠標懸停在其上時,很容易突出顯示div懸停突出顯示分層div

但是,當div s在彼此內部時,父母對div的其餘部分進行遮蔽。我應該如何讓CSS懸停在直接懸停的div上?

當我將鼠標懸停在parrot上時,我不想讓birdanimal突出顯示。

div.creature{ 
 
    margin:5px; 
 
    padding:5px; 
 
    border: 1px solid; 
 
} 
 
div.creature:hover{ 
 
    background: #ffeeaa; 
 
}
<div class="creature"> 
 
    animal 
 
    <div class="creature"> 
 
    mammal 
 
    <div class="creature"> 
 
    cat 
 
    </div> 
 
    </div> 
 
    <div class="creature"> 
 
    bird 
 
    <div class="creature"> 
 
    parrot 
 
    </div> 
 
    <div class="creature"> 
 
    duck 
 
    </div> 
 
    </div> 
 
</div>

UPDATE

的HTML代碼是動態創建的。因此,獨立的CSS是首選。

當我徘徊在bird而不是parrotduck,我期望整個bird亮點。

回答

2

這樣的事情?

更新:添加一個jQuery功能

$(function() { 
 
    $('div').on('mouseover', function(e){ 
 
     e.stopPropagation(); 
 
     $(this).addClass('my-bg'); 
 
    }).on('mouseout', function(e){ 
 
     $(this).removeClass('my-bg'); 
 
    }) 
 
});
div.creature{ 
 
    margin:5px; 
 
    padding:5px; 
 
    border: 1px solid; 
 
} 
 

 
.my-bg{ 
 
    background-color: #ffeeaa; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="creature"> 
 
    animal 
 
    <div class="creature"> 
 
    mammal 
 
    <div class="creature"> 
 
    cat 
 
    </div> 
 
    </div> 
 
    <div class="creature"> 
 
    bird 
 
    <div class="creature"> 
 
    parrot 
 
    </div> 
 
    <div class="creature"> 
 
    duck 
 
    </div> 
 
    </div> 
 
</div>

+0

非常感謝你。有兩個問題。我預計,在「鳥」或「哺乳動物」本身上盤旋,突出他們的整個「div」。 'div'也是動態創建的。因此,我不知道在CSS中寫什麼。 – ar2015

+0

我已經更新了我的答案。現在它按照你的期望工作。已經添加了一個額外的jQuery函數,所以不要忘記將jQuery文件包含在您的項目中。 – Saurabh

+0

非常感謝。如果我動態地向「div」添加內容,是否需要再次運行jquery代碼? – ar2015

1

這是接近我可以得到的。我用:nth-of-type

剩下的工作就是關閉父背景時,其孩子中的一個是在:hover狀態,這我不認爲 CSS支持,因爲它doesn't have parent selectors

這不應該是問題太難用JS

div.fruit { 
 
    margin: 5px; 
 
    padding: 5px; 
 
    border: 1px solid; 
 
    background:white; /* otherwise the divs have no background */ 
 
} 
 

 
.fruit:hover { 
 
    background: red; /* Main parent div */ 
 
} 
 

 
.fruit > div:nth-of-type(1):hover { 
 
    background: blue; /* First child div */ 
 
} 
 

 
.fruit > div:nth-of-type(1):hover > div:nth-of-type(1):hover { 
 
    background: green; /* First grandchild div */ 
 
} 
 

 
.fruit > div:nth-of-type(2):hover { 
 
    background: yellow; /* second child div */ 
 
} 
 

 
.fruit > div:nth-of-type(3):hover { 
 
    background: orange; /* third child div */ 
 
}
<div class="fruit">A1 
 
    <div class="fruit">AA1 
 
    <div class="fruit">AAA1</div> 
 
    </div> 
 
    <div class="fruit">AA2</div> 
 
</div>

0

他們正在做WH修復在你想要的時候。你只是忘了在它們上面設置一個背景顏色,所以它們會顯示在下面的div上。這裏是一個小提琴證明這一點:

div.creature{ 
    margin:5px; 
    padding:5px; 
    border: 1px solid; 
    background: #F3F5F6 
} 
div.creature:hover{ 
    background: #FFEEAA; 
} 

https://jsfiddle.net/shavedave1/ucvvcrer/1/

+0

誤讀你的問題陳述 - 看起來你實際上並不希望父容器在你的子容器中被高亮顯示。 – David