如何使用Javascript添加CSS规则(如强{颜色:红色})?
当前回答
这个简单的例子在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
其他回答
在现代浏览器中,您可以使用document。adoptedStyleSheets添加CSS。
const sheet = new CSSStyleSheet();
sheet.replace("strong { color: red; }");
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
这种方法的一个优点是,您甚至不需要等待<head>元素可用,这可能是早期运行的浏览器扩展代码所关注的问题。
最短一行 //一个函数: const addCSS =css => document.head.appendChild(document.createElement("style")).innerHTML=css; / /使用方法: addCSS(“身体{背景:红色;}”)
您可以逐个元素添加类或样式属性。
例如:
<a name="myelement" onclick="this.style.color='#FF0';">text</a>
你可以这样做。背景,this.style。字体大小等。你也可以使用同样的方法应用一个样式
this.className='classname';
如果你想在javascript函数中做到这一点,你可以使用getElementByID而不是'this'。
YUI最近专门为此添加了一个实用程序。点击这里查看stylesheet.js。
你也可以使用DOM Level 2 CSS接口(MDN):
var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);
...除了IE8和更早的版本,它使用了自己略微不同的措辞:
sheet.addRule('strong', 'color: red;', -1);
与createElement-set-innerHTML方法相比,这种方法有一个理论上的优势,因为您不必担心在innerHTML中放入特殊的HTML字符,但实际上样式元素是遗留HTML中的CDATA,而且' < '和' & '很少在样式表中使用。
在开始像这样向它追加内容之前,确实需要一个样式表。这可以是任何现有的活动样式表:外部的、嵌入式的或空的,这都没有关系。如果没有,目前创建它的唯一标准方法是使用createElement。