2013-01-22 13 views
0

我要重寫的鏈接列表上我的CSS懸停動作時div容器,在這種情況下的#header,有0.5的不透明度。我有一段困難的時光。無法在jquery中選擇不透明度?

這裏是我的jQuery:

jQuery(window).scroll(function() { 
    if(jQuery(window).scrollTop() > 200) { 
     jQuery("#header").css('opacity', '0.5'); 
    } else { 
     jQuery("#header").css('opacity','1'); 
    } 
    }); 

    if(jQuery("#header").css("opacity") != 1){ 
     jQuery("#nav li a").hover(function(){ 
     jQuery(this).css("color","rgba(63, 131, 202, 1)"); 
     }); 
    } 

,這裏是我的CSS:

#nav li a { 
    color:rgba(63, 131, 202, 1); 
    transition: color 1s; 
    -webkit-transition: color 1s; 
    -o-transition: color 1s; 
    -moz-transition: color 1s; 
} 

#nav li a:hover { 
    color:rgba(63, 131, 202, 0.7); 
    transition: color 1s; 
    -webkit-transition: color 1s; 
    -o-transition: color 1s; 
    -moz-transition: color 1s; 
} 

我也試着重寫與沒有jQuery中每一個過渡,但它不工作。我怎麼能這樣做?我應該嘗試在不透明度不爲1,覆蓋所有沒有懸停的屬性,然後重寫懸停屬性,如我上面做?不知道該怎麼辦。

回答

1

我建議在CSS中保留儘可能多的樣式,並簡單地修改需要更改的元素(或者在層次結構中較高的元素上,如body,如果它要更改多個元素),請修改class, 。這裏有一個例子:

的Javascript:

jQuery(window).scroll(function() { 
    jQuery(document.body).toggleClass("scrolledDown", jQuery(window).scrollTop() > 200) 
}); 

CSS

#nav li a { 
    color:rgba(63, 131, 202, 1); 
    transition: color 1s; 
    -webkit-transition: color 1s; 
    -o-transition: color 1s; 
    -moz-transition: color 1s; 
} 

#nav li a:hover { 
    color:rgba(63, 131, 202, 0.7); 
    transition: color 1s; 
    -webkit-transition: color 1s; 
    -o-transition: color 1s; 
    -moz-transition: color 1s; 
} 

#header { 
    opacity: 1; 
} 

body.scrolledDown #header { 
    opacity: 0.5; 
} 

body.scrolledDown #nav li a:hover { 
    color: rgba(63, 131, 202, 1); 
} 

這將自動管理您的狀態,從而保持自己的風格和JavaScript分開,這總是好的。您不必到class添加到body元素,但我做到了這裏一個簡單的例子,你缺乏DOM結構的其餘部分知識的緣故。

+0

很好的答案。謝謝!我唯一想知道的是將scrolledDown添加到我的#header div的最佳方式。 –

+0

這取決於。如您所見,導航的鏈接懸停要求將scrolledDown類放在其層次結構中以影響它。如果你的'#nav'是你的'#header'的一個孩子(無論多深),你當然可以將它添加到'#header' div。否則,你需要找到一個共同的祖先。我選擇了'body',因爲我知道它將是一個共同的祖先,而不管你的DOM。 :) –

+0

想通了。我問了如何將它添加到我的#header div中,因爲我的嘗試不起作用,但我忘了添加分號。我是認真的。 :) –

1

作爲一種變通方法,你很可能有更多的成功與:

jQuery("#header").fadeTo(0, 0.5); 

代替:

jQuery("#header").css('opacity', '0.5'); 
+0

謝謝,我會嘗試。 –

+0

fadeTo有一些非常奇怪的問題。在這裏上下滾動,你會看到我的意思:http://tommaxwell.co/ –

1

通過調試您的調試代碼是在這樣的情況下非常有用。在這個特殊的情況下,你會發現,jQuery.fn.css()返回,甚至如果要查詢一個數字CSS屬性的字符串,所以你要parseFloat()的結果。

if(parseFloat(jQuery("#header").css("opacity")) != 1) 

也就是說,我強烈建議放棄查詢樣式屬性,並使用類來管理您的狀態。演示文稿不是信息!作爲獎勵,您的鏈接懸停可能只是基於類名的基於css的覆蓋,而不是javascript動力懸停。

+0

哦,真的嗎?我認爲它會返回一個字符串,但從另一個SO線程得到了這個想法。 –

+0

我在Chrome檢查剛纔:$(「身體」)的CSS(「不透明」) >「1」 –

+0

我不得不開始使用更頻繁。 –