2016-01-26 40 views
0

在我的網頁我想設置的屬性顯示,以block!important當有URL中的特定字符串設置CSS屬性爲重要,通過JavaScript

我一直在做一些研究,但找不到正確答案。使用下面的代碼,我可以在身上設置background-color: green!important,但我不知道如何定位其他內容("loginActive" id元素)。

:javascript 
    if(window.location.href.indexOf("sign_up") > -1) { 
    document.body.style.setProperty ("background-color", "green", "important"); 
    document.getElementById("loginActive").style.display = "block", "important"; 
    } 

我如何能設置元素#loginActivedisplay: block!important任何提示嗎?

+2

你不應該需要使用'!important'如果你設定的風格元素本身,除非其他地方有其他東西是'!important'。如果其他地方是'重要的',那麼可能是誰加了它就決定不應該被推翻。一般來說,使用'!important'被認爲是CSS問題的一個不好的解決方案,它會回來咬你,因爲它聽起來可能已經在這裏完成了。 –

+0

你可以用Jquery嗎? – simon

+0

我並不喜歡使用!重要的,但我用它與角度ng顯示功能。 – alucardu

回答

1

試試這個

var item = document.getElementById("loginActive"); 
item.style. display = 'block !important'; 

或者

item.setAttribute('style', 'display:block !important'); 

但你不應該這樣做

+0

這與'document.getElementById(「loginActive」)。style.display =「block」,「important」;' – alucardu

+0

'沒有區別:javascript if(window.location.href.indexOf(「sign_up」)> -1) {var item = document.getElementById(「loginActive」); item.style.setProperty(「display」,「block」,「important」); }'改了一下代碼,現在就工作。 – alucardu

+0

我的不好,setAttribute實際上效果更好,但你應該考慮使用一個帶顯示的類:!important並附加到元素 – HoangND