2016-04-25 92 views
0

我試圖做出從中是 徘徊元素列表元素透明度變化 我的HTML標記如何從懸停的列表元素中設置下一個相鄰,前一個相鄰列表元素和其他列表元素的樣式?

  <ul class="list-unstyled"> 
      <li> 
       Lorem ipsum dolor sit amet 
      </li> 
      <li> 
       Consectetur adipiscing elit 
      </li> 
      <li> 
       Integer molestie lorem at massa 
      </li> 
      <li> 
       Facilisis in pretium nisl aliquet 
      </li> 
      <li> 
       Nulla volutpat aliquam velit 
      </li> 
      <li> 
       Faucibus porta lacus fringilla vel 
      </li> 
      <li> 
       Aenean sit amet erat nunc 
      </li> 
      <li> 
       Eget porttitor lorem 
      </li> 
     </ul> 

在那裏我使用這個CSS

.list-unstyled li:first-of-type { 
    opacity:1; 
} 
.list-unstyled li:nth-of-type(2){ 
    opacity:0.60; 
} 
.list-unstyled li:nth-of-type(3){ 
opacity:0.35; 
} 
.list-unstyled li { 
    opacity:0.35; 
} 
.list-unstyled li:hover { 
    opacity:1 !important; 
} 
.list-unstyled li:hover ~ li { 
opacity:0.65 !important; 
} 
.list-unstyled li:hover ~ li ~li { 
opacity:0.35 !important; 
} 

我要讓懸停的元素直接兄弟姐妹有35%的不透明層 ,對他們休息應該有65%的不透明層。

,而在初始階段欲第一li元素具有不透明層爲1並且當其爲unhovered其它元件盤旋我怎樣才能實現這一點應該改變到相應的樣式。

+0

相關(但不是一個確切的重複):http://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-css-selector – Matt

回答

-1

如果它是一個直接的兄弟姐妹,你可以使用+選擇。 那麼任何兄弟姐妹,是不是一個立即的兄弟姐妹可以使用~選擇

.list-unstyled li:hover + li { 
    opacity:0.35; 
} 

.list-unstyled li:hover ~ li { 
    opacity:0.65; 
} 
+0

但是使用這種方法,我們只能選擇徘徊的元素。以前的元素呢? –

+0

這是一直以來的痛苦。此外,選擇父母,而不是僅僅是孩子會很高興。 在這種情況下,我想知道你是否可以使用:not(:hover) –

2

CSS沒有以前的兄弟選擇您想達到這樣什麼是不可能單獨使用CSS。

如果你是開放的一個JavaScript的解決方案,你可以做這樣的:

var \t items=document.getElementsByTagName("li"), 
 
    hovered=items[0], 
 
    x=items.length, 
 
    previous; 
 
hovered.classList.add("hovered"); 
 
while(x--) 
 
    items[x].addEventListener("mouseover",function(){ 
 
     hovered.classList.remove("hovered"); 
 
     if(previous) 
 
      previous.classList.remove("previous"); 
 
     hovered=this; 
 
     previous=this.previousSibling; 
 
     hovered.classList.add("hovered"); 
 
     if(previous) 
 
      previous.classList.add("previous"); 
 
    },0);
ul{list-style:none;margin:0;padding:0;} 
 
li{width:100px;height:100px;background:red;display:inline-block;} 
 
li{ 
 
    opacity:0.35; 
 
    transition:opacity .25s; 
 
} 
 
.hovered{ 
 
    opacity:1; 
 
} 
 
.previous,.hovered+li{ 
 
    opacity:.65; 
 
}
<ul><li></li><li></li><li></li><li></li><li></li></ul>

1

你只需要添加更多的CSS代碼

.list-unstyled:hover li:first-of-type { 
    opacity:.35; 
} 

這裏是工作demo您的問題

相關問題