如何使用Javascript添加CSS规则(如强{颜色:红色})?
当前回答
最短一行 //一个函数: const addCSS =css => document.head.appendChild(document.createElement("style")).innerHTML=css; / /使用方法: addCSS(“身体{背景:红色;}”)
其他回答
最短一行 //一个函数: const addCSS =css => document.head.appendChild(document.createElement("style")).innerHTML=css; / /使用方法: addCSS(“身体{背景:红色;}”)
如果你知道页面中至少存在一个<style>标签,使用这个函数:
CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};
用法:
CSS("div{background:#00F}");
您可以逐个元素添加类或样式属性。
例如:
<a name="myelement" onclick="this.style.color='#FF0';">text</a>
你可以这样做。背景,this.style。字体大小等。你也可以使用同样的方法应用一个样式
this.className='classname';
如果你想在javascript函数中做到这一点,你可以使用getElementByID而不是'this'。
这是Chris Herring的解决方案的一个稍微更新的版本,考虑到你也可以使用innerHTML,而不是创建一个新的文本节点:
function insertCss( code ) {
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
// IE
style.styleSheet.cssText = code;
} else {
// Other browsers
style.innerHTML = code;
}
document.getElementsByTagName("head")[0].appendChild( style );
}
这个简单的例子在html头部添加<style>
var sheet = document.createElement('style');
sheet.innerHTML = "table th{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ "table ul { margin-top: 0 !important; margin-bottom: 0 !important;}\n"
+ "table td{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ ".messages.error{display:none !important;}\n"
+ ".messages.status{display:none !important;} ";
document.body.appendChild(sheet); // append in body
document.head.appendChild(sheet); // append in head
动态样式——用JavaScript操作CSS