如何使用Javascript添加CSS规则(如强{颜色:红色})?
简单而直接的方法是在文档中创建并添加一个新的样式节点。
// Your CSS as text
var styles = `
.qwebirc-qui .ircwindow div {
font-family: Georgia,Cambria,"Times New Roman",Times,serif;
margin: 26px auto 0 auto;
max-width: 650px;
}
.qwebirc-qui .lines {
font-size: 18px;
line-height: 1.58;
letter-spacing: -.004em;
}
.qwebirc-qui .nicklist a {
margin: 6px;
}
`
var styleSheet = document.createElement("style")
styleSheet.innerText = styles
document.head.appendChild(styleSheet)
你也可以使用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。
您可以逐个元素添加类或样式属性。
例如:
<a name="myelement" onclick="this.style.color='#FF0';">text</a>
你可以这样做。背景,this.style。字体大小等。你也可以使用同样的方法应用一个样式
this.className='classname';
如果你想在javascript函数中做到这一点,你可以使用getElementByID而不是'this'。
本·布兰克(Ben Blank)的解决方案在IE8中不适合我。
然而,这在IE8中是有效的
function addCss(cssCode) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = cssCode;
} else {
styleElement.appendChild(document.createTextNode(cssCode));
}
document.getElementsByTagName("head")[0].appendChild(styleElement);
}
这是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 );
}
下面是我的通用函数,它参数化了CSS选择器和规则,如果你想添加到特定的表中,它还可以选择一个CSS文件名(区分大小写)(否则,如果你不提供CSS文件名,它将创建一个新的样式元素并将其附加到现有的头部)。它最多创建一个新的样式元素,并在以后的函数调用中重用它)。适用于FF, Chrome和IE9+(可能更早,未经测试)。
function addCssRules(selector, rules, /*Optional*/ sheetName) {
// We want the last sheet so that rules are not overridden.
var styleSheet = document.styleSheets[document.styleSheets.length - 1];
if (sheetName) {
for (var i in document.styleSheets) {
if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(sheetName) > -1) {
styleSheet = document.styleSheets[i];
break;
}
}
}
if (typeof styleSheet === 'undefined' || styleSheet === null) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
document.head.appendChild(styleElement);
styleSheet = styleElement.sheet;
}
if (styleSheet) {
if (styleSheet.insertRule)
styleSheet.insertRule(selector + ' {' + rules + '}', styleSheet.cssRules.length);
else if (styleSheet.addRule)
styleSheet.addRule(selector, rules);
}
}
另一种选择是使用JQuery存储元素的内联样式属性,然后附加到它,然后用新值更新元素的样式属性。如下:
function appendCSSToElement(element, CssProperties)
{
var existingCSS = $(element).attr("style");
if(existingCSS == undefined) existingCSS = "";
$.each(CssProperties, function(key,value)
{
existingCSS += " " + key + ": " + value + ";";
});
$(element).attr("style", existingCSS);
return $(element);
}
然后用新的CSS属性作为对象执行它。
appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });
这可能不是最有效的方法(我愿意接受关于如何改进这一点的建议。:)),但它绝对有效。
这个简单的例子在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
这是我在最后一个样式表列表的末尾添加css规则的解决方案:
var css = new function()
{
function addStyleSheet()
{
let head = document.head;
let style = document.createElement("style");
head.appendChild(style);
}
this.insert = function(rule)
{
if(document.styleSheets.length == 0) { addStyleSheet(); }
let sheet = document.styleSheets[document.styleSheets.length - 1];
let rules = sheet.rules;
sheet.insertRule(rule, rules.length);
}
}
css.insert("body { background-color: red }");
在Jquery中使用。css,例如$('strong').css('background','red');
$(“强”). css(“背景”、“红色”); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < >强的例子 < / >强
下面是一个示例模板来帮助您入门
不需要任何库,只使用javascript注入HTML和CSS。
这个函数是从上面的@Husky用户那里借来的
如果你想运行一个tampermonkey脚本,并想在网站上添加一个切换覆盖(例如,一个笔记应用程序),这很有用。
// INJECTING THE HTML document.querySelector('body').innerHTML += '<div id="injection">Hello World</div>'; // CSS INJECTION FUNCTION //https://stackoverflow.com/questions/707565/how-do-you-add-css-with-javascript 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 ); } // INJECT THE CSS INTO FUNCTION // Write the css as you normally would... but treat it as strings and concatenate for multilines insertCss( "#injection {color :red; font-size: 30px;}" + "body {background-color: lightblue;}" )
如果你知道页面中至少存在一个<style>标签,使用这个函数:
CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};
用法:
CSS("div{background:#00F}");
最短一行 //一个函数: const addCSS =css => document.head.appendChild(document.createElement("style")).innerHTML=css; / /使用方法: addCSS(“身体{背景:红色;}”)
我总是忘记如何添加一个类的HTML元素,这个SO出现在谷歌早期,但没有人添加这样做的现代方式,所以在这里。
要添加一个CSS样式,你可以选择元素并调用.classList.add(<className>)
例如: document.querySelector .classList.add(“#主要”)(“bg-primary”);
你可能还需要删除其他与你所添加的类冲突的类。 document.querySelector .classList.remove(“#主要”)(“bg-secondary”);
就是这样。运行示例,您将看到setInterval()方法每3秒添加&删除一次样式。
let useSecondary = false; setInterval(changeBgColor, 3000); function changeBgColor(){ if (useSecondary){ document.querySelector("#main").classList.remove("bg-primary"); document.querySelector("#main").classList.add("bg-secondary"); } else{ document.querySelector("#main").classList.remove("bg-secondary"); document.querySelector("#main").classList.add("bg-primary"); } useSecondary = !useSecondary; } * { transition: all 0.5s ease-in-out; } .bg-primary { background-color: green; } .bg-secondary{ background-color: yellow; } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div > <div id="main" > Example text has background color changed every 3 seconds by adding / removing CSS styles. </div> </div> </body> </html>
在现代浏览器中,您可以使用document。adoptedStyleSheets添加CSS。
const sheet = new CSSStyleSheet();
sheet.replace("strong { color: red; }");
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
这种方法的一个优点是,您甚至不需要等待<head>元素可用,这可能是早期运行的浏览器扩展代码所关注的问题。