2016-03-10 46 views
0

我在我的網站的每個頁面上都有一個帶有特定ID(「容器」)的DIV作爲模板的一部分。雖然css仍然適用,但使用JavaScript添加和刪除div樣式

#container 
{ 
max-width:980px; min-width:980px; padding-top:6px; 
} 

當一個按鈕(切換全屏)點擊我得到的是客戶端的最大支持的寬度,然後做:

document.getElementById('container').setAttribute('style', 'max-width:' + width + 'px !important;'); 
document.getElementById('container').setAttribute('style', 'min-width:' + width + 'px !important;'); 

這工作得很好,並設置最大寬度來說1400px。

我的問題是,我可以刪除我剛剛添加的這種風格,所以只有css會應用,使用JavaScript?

或者是我的選擇有相同的代碼,回到980?

document.getElementById('container').setAttribute('style', 'max-width:980px !important;'); 
document.getElementById('container').setAttribute('style', 'min-width:980px !important;'); 
+0

像素是強制性的嗎?你爲什麼不以自己的單位爲基礎?爲什麼!重要?你會更好地使用CSS類,基於全屏模式有條件地應用。 –

+0

我會做一個「全屏」的CSS類,它將覆蓋默認的#容器樣式。然後,您可以在全屏時簡單地向您的元素添加類名,並在不添加時將其刪除。 – James

回答

2

您可以刪除整個style屬性

document.getElementById('container').removeAttribute('style'); 

或者你可以在style屬性只取出max-width屬性:

document.getElementById('container').style.maxWidth = "none"; 

參考文獻的:

style

removeAttribute

+1

輝煌的,我害怕這樣的事情也會刪除任何CSS,它不會。 –

+0

這不會刪除CSS,這會操縱DOM'style'屬性,它會覆蓋已定義的CSS樣式,但不會更改您的css文件中的任何內容。 –

+0

它只刪除內聯樣式。 –

2

我的問題是,我可以刪除這個風格我只是說,所以纔有了CSS 將適用,使用JavaScript?

您需要使用此一類

.default-style 
{ 
    max-width:980px; min-width:980px; padding-top:6px; 
} 

因此而賦予新的寬度,刪除該類第一

document.getElementById('container').setAttribute('style', 'max-width:' + width + 'px;min-width:' + width + 'px;'); 
document.getElementById('container').classList.remove("default-style"); 

當你想回到默認

document.getElementById('container').removeAttribute('style'); 
document.getElementById('container').classList.add('default-style'); 

請參閱Element.classList添加/ rem上課。

+0

我的觀點正是如此。但是,重要的是一個壞習慣。如果需要,最大寬度可以重置爲默認瀏覽器值。 –

+0

@Bonatoc刪除了'!important'。現在不需要。我同意它應該非常仔細地使用 – gurvinder372

+0

我怕這不是由@Bonatoc downvoted。我感覺像LOL –

相關問題