2017-03-16 21 views
0

我試圖動畫元素上懸停背景色,反而使文本保持始終可見/在上面,我不能做到這一點。似乎設置z-index沒有做任何事情。還有什麼我應該嘗試做的?如何在懸停時擁有不同的背景動畫時始終顯示文本?

ul li { 
 
    background-color: #eee; 
 
    padding: 10px; 
 
    position: relative; 
 
    width: 200px; 
 
} 
 

 
ul li:hover .bg:before { 
 
    width: 50%; 
 
} 
 

 
.text { 
 
    z-index: 999999999; 
 
    color: #fff; 
 
    text-shadow: 1px 1px 1px #333; 
 
    display: inline-block; 
 
} 
 

 
.bg:before { 
 
    content: '\A'; 
 
    position: absolute; 
 
    background: black; 
 
    top: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    width: 2%; 
 
    transition: all 2s; 
 
}
<ul> 
 
    <li> 
 
    <div class="text">Hover over this text</div> 
 
    <div class="bg"></div> 
 
    </li> 
 
</ul>

回答

3

z-index不會影響文本元素,因爲它是靜態定位爲相對應的是絕對定位的BG元素。爲了解決這個問題,你可以添加position: relative;對文本元素:

ul li { 
 
    background-color: #eee; 
 
    padding: 10px; 
 
    position: relative; 
 
    width: 200px; 
 
} 
 

 
ul li:hover .bg:before { 
 
    width: 50%; 
 
} 
 

 
.text { 
 
    z-index: 999999999; 
 
    color: #fff; 
 
    text-shadow: 1px 1px 1px #333; 
 
    display: inline-block; 
 
    position: relative; 
 
} 
 

 
.bg:before { 
 
    content: '\A'; 
 
    position: absolute; 
 
    background: black; 
 
    top: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    width: 2%; 
 
    transition: all 2s; 
 
}
<ul> 
 
    <li> 
 
    <div class="text">Hover over this text</div> 
 
    <div class="bg"></div> 
 
    </li> 
 
</ul>

1

z-index僅適用於定位的元素如:

  • 位置:絕對
  • 位置:相對於
  • 位置是:固定

所以加position: relative;.text

ul li { 
 
    background-color: #eee; 
 
    padding: 10px; 
 
    position: relative; 
 
    width: 200px; 
 
} 
 

 
ul li:hover .bg:before { 
 
    width: 50%; 
 
} 
 

 
.text { 
 
    position: relative; 
 
    z-index: 2; 
 
    color: #fff; 
 
    text-shadow: 1px 1px 1px #333; 
 
    display: inline-block; 
 
} 
 

 
.bg:before { 
 
    content: '\A'; 
 
    position: absolute; 
 
    background: black; 
 
    top: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    width: 2%; 
 
    transition: all 2s; 
 
}
<ul> 
 
    <li> 
 
    <div class="text">Hover over this text</div> 
 
    <div class="bg"></div> 
 
    </li> 
 
</ul>