[英]How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?
如果我的html中有以下內容:
<div style="height:300px; width:300px; background-color:#ffffff;"></div>
這在我的css樣式表中:
div {
width:100px;
height:100px;
background-color:#000000;
}
有沒有辦法,使用javascript / jquery,刪除所有內聯樣式,只留下由CSS樣式表指定的樣式?
$('div').attr('style', '');
要么
$('div').removeAttr('style');
(來自Andres的回答 )
為了使它更小一點,試試這個:
$('div[style]').removeAttr('style');
這應該加快一點,因為它檢查div有樣式屬性。
無論哪種方式,如果你有大量的div,這可能需要一些時間來處理,所以你可能想要考慮除了javascript之外的其他方法。
普通的JavaScript:
你不需要jQuery來做這樣的微不足道的事情。 只需使用.removeAttribute()
方法即可。
假設您只是針對單個元素,您可以輕松使用以下內容:( 示例)
document.querySelector('#target').removeAttribute('style');
如果您要定位多個元素,只需遍歷選定的元素集合:( 示例)
var target = document.querySelectorAll('div');
Array.prototype.forEach.call(target, function(element){
element.removeAttribute('style');
});
Array.prototype.forEach()
- IE9及以上/ .querySelectorAll()
- IE 8(部分)IE9及以上版本。
$('div').removeAttr('style');
如果您只需要清空元素的style
,那么:
element.style.cssText = null;
這應該做得很好。 希望能幫助到你!
我正在使用$('div').attr('style', '');
技術,它在IE8中不起作用。
我使用alert()
輸出了style屬性,並沒有刪除內聯樣式。
.removeAttr
最終在IE8中完成了這個技巧。
這可以通過兩個步驟完成:
1:通過標記名,ID,類等選擇要更改的元素。
var element = document.getElementsByTagName('h2')[0];
element.removeAttribute('style');
您還可以嘗試將樣式表中的css列為!important
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.