是否可以使用 JavaScript 更改 CSS 样式表?
我不是在谈论:
document.getElementById('id').style._____='.....';
我AM谈论改变:
#id {
param: value;
}
除了做一些肮脏的事情(顺便说一句,我们还没有尝试过),比如在头部创建一个新对象,在里面创建一个 style 标签,等等。尽管这样做,即使它确实有效,也会带来一些问题作为样式块已在别处定义,我不确定浏览器何时/是否会解析动态创建的样式块?
是否可以使用 JavaScript 更改 CSS 样式表?
我不是在谈论:
document.getElementById('id').style._____='.....';
我AM谈论改变:
#id {
param: value;
}
除了做一些肮脏的事情(顺便说一句,我们还没有尝试过),比如在头部创建一个新对象,在里面创建一个 style 标签,等等。尽管这样做,即使它确实有效,也会带来一些问题作为样式块已在别处定义,我不确定浏览器何时/是否会解析动态创建的样式块?
是的,您可以,但您将面临跨浏览器兼容性问题:
http://www.quirksmode.org/dom/changess.html
浏览器支持有了很大改进(支持所有浏览器,包括 IE9+)。
该insertRule()方法允许向样式表动态添加规则。
使用deleteRule(),您可以从样式表中删除现有规则。
可以通过cssRules样式表的属性访问样式表中的规则。
我们可以使用的组合.insertRule,并.cssRules能够做到这一切的回到IE9方式:
function changeStylesheetRule(stylesheet, selector, property, value) {
// Make the strings lowercase
selector = selector.toLowerCase();
property = property.toLowerCase();
value = value.toLowerCase();
// Change it if it exists
for(var i = 0; i < stylesheet.cssRules.length; i++) {
var rule = stylesheet.cssRules[i];
if(rule.selectorText === selector) {
rule.style[property] = value;
return;
}
}
// Add it if it does not
stylesheet.insertRule(selector + " { " + property + ": " + value + "; }", 0);
}
// Used like so:
changeStylesheetRule(s, "body", "color", "rebeccapurple");
当我想以编程方式向对象添加一堆样式时,我发现以编程方式向对象添加类更容易(此类类在您的 CSS 中具有与其相关的样式)。您可以控制 CSS 中的优先顺序,以便新类中的新样式可以覆盖您以前拥有的样式。这通常比直接修改样式表容易得多,并且可以完美地跨浏览器工作。
更改样式规则中的属性
function change_css_style (titulo,selector,propiedad,valor) {
let i=0;
while (i<document.styleSheets.length) {
if (document.styleSheets[i].title==titulo) {
let y=0;
while (y<document.styleSheets[i].cssRules.length) {
if (document.styleSheets[i].cssRules[y].selectorText==selector) {
document.styleSheets[i].cssRules[y].style[propiedad] = valor;
y = document.styleSheets[i].cssRules.length;
}
y++;
}
i=document.styleSheets.length;
}
i++;
}
}
演示
<style title="chat_inicio">
.contenido .mensajes {
width: 100px;
height: 300px;
}
</style>
转变作风书标题chat_inicio与选择.contenido .mensajes风格的财产宽度到475px
<script>
cambiar_css_style ('chat_inicio','.contenido .mensajes','width','475px');
</script>
这种方法的一些优点:
!important属性用法:
adjustCSSRules('#myDiv', 'width: 300px !important');
方法:
function adjustCSSRules(selector, props, sheets){
// get stylesheet(s)
if (!sheets) sheets = [...document.styleSheets];
else if (sheets.sup){ // sheets is a string
let absoluteURL = new URL(sheets, document.baseURI).href;
sheets = [...document.styleSheets].filter(i => i.href == absoluteURL);
}
else sheets = [sheets]; // sheets is a stylesheet
// CSS (& HTML) reduce spaces in selector to one.
selector = selector.replace(/\s+/g, ' ');
const findRule = s => [...s.cssRules].reverse().find(i => i.selectorText == selector)
let rule = sheets.map(findRule).filter(i=>i).pop()
const propsArr = props.sup
? props.split(/\s*;\s*/).map(i => i.split(/\s*:\s*/)) // from string
: Object.entries(props); // from Object
if (rule) for (let [prop, val] of propsArr){
// rule.style[prop] = val; is against the spec, and does not support !important.
rule.style.setProperty(prop, ...val.split(/ *!(?=important)/));
}
else {
sheet = sheets.pop();
if (!props.sup) props = propsArr.reduce((str, [k, v]) => `${str}; ${k}: ${v}`, '');
sheet.insertRule(`${selector} { ${props} }`, sheet.cssRules.length);
}
}
该方法接受三个参数:
.myClass #myDiv将匹配.myClass #myDiv){ border: "solid 3px green", color: "white" }'border: solid 3px green; color: white'document.styleSheets[1] - 对工作表的引用其他例子:
adjustCSSRules('#myDiv', {width: '30px'}); // all stylesheets
adjustCSSRules('#myDiv', 'width: 30px', 'style.css'); // style.css only
adjustCSSRules('#myDiv .myClass', 'width: 30px', document.styleSheets[0]); // only first stylesheet