使用 Javascript 更改 CSS 值

IT技术 javascript html css ajax dom
2021-02-09 21:05:43

使用 javascript 设置内联 CSS 值很容易。如果我想更改宽度并且我有这样的 html:

<div style="width: 10px"></div>

我需要做的就是:

document.getElementById('id').style.width = value;

它将更改内联样式表值。通常这不是问题,因为内联样式会覆盖样式表。例子:

<style>
   #tId {
      width: 50%;
   }
</style>

<div id="tId"></div>

使用这个 Javascript:

document.getElementById('tId').style.width = "30%";

我得到以下信息:

<style>
   #tId {
      width: 50%;
   }
</style>

<div id="tId" style="width: 30%";></div>

这是一个问题,因为我不仅不想更改内联值,如果我在设置之前查找宽度,当我有:

<div id="tId"></div>

返回的值是 Null,所以如果我有 Javascript 需要知道某些东西的宽度来做一些逻辑(我将宽度增加 1%,而不是特定值),当我期望字符串“50%”时返回 Null "真的不行。

所以我的问题是:我的 CSS 样式中的值不是内联的,我怎样才能获得这些值?给定 id,如何修改样式而不是内联值?

6个回答

好的,听起来您想更改全局 CSS,以便一次有效地更改特定样式的所有元素。我最近从Shawn Olson 教程中学会了如何自己做到这一点你可以在这里直接引用他的代码

这是摘要:

您可以通过检索样式表document.styleSheets这实际上将返回页面中所有样式表的数组,但您可以通过该document.styleSheets[styleIndex].href属性判断您使用的是哪个样式表找到要编辑的样式表后,您需要获取规则数组。这在 IE 中称为“规则”,在大多数其他浏览器中称为“cssRules”。告诉你使用什么CSSRule的方法是通过selectorText属性。工作代码如下所示:

var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
var selector = rule.selectorText;  //maybe '#tId'
var value = rule.value;            //both selectorText and value are settable.

让我知道这对你是如何工作的,如果你看到任何错误,请发表评论。

2021-03-25 21:05:43
document.styleSheets[styleIndex].cssRules.[ruleIndex].style = {'color':'red', 'background-color':'green'}; 为我工作,谢谢!
2021-03-25 21:05:43
这太棒了!我正在研究图像转换,当您开始将大图像放入 36 个单独的 URI 进行切片时,CSS 确实变慢了。这只是从我的脚本中减少了大量开销。谢谢!
2021-03-27 21:05:43
rule.value在 FF 20 中找不到rule.style但是,它是可设置的,其行为类似于element.style. 参见 https://developer.mozilla.org/en-US/docs/DOM/CSSStyleRule检查rule.type == rule.STYLE_RULE也可能是访问前一个好主意rule.selectorText
2021-04-03 21:05:43
如果您有 100 多个元素,以这种方式更改 CSS更快。例如,一次更改表格某个部分中的所有单元格。
2021-04-07 21:05:43

请!问问w3(http://www.quirksmode.org/dom/w3c_css.html)!或者实际上,我花了五个小时......但它来了!

function css(selector, property, value) {
    for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles
        //Try add rule
        try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);
        } catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE
    }
}

该功能非常易于使用..示例:

<div id="box" class="boxes" onclick="css('#box', 'color', 'red')">Click Me!</div>
Or:
<div class="boxes" onmouseover="css('.boxes', 'color', 'green')">Mouseover Me!</div>
Or:
<div class="boxes" onclick="css('body', 'border', '1px solid #3cc')">Click Me!</div>

哦..


编辑:正如@user21820 在其回答中所述,更改页面上的所有样式表可能有点不必要。以下脚本适用于 IE5.5 以及最新的 Google Chrome,并且仅添加了上述 css() 函数。

(function (scope) {
    // Create a new stylesheet in the bottom
    // of <head>, where the css rules will go
    var style = document.createElement('style');
    document.head.appendChild(style);
    var stylesheet = style.sheet;
    scope.css = function (selector, property, value) {
        // Append the rule (Major browsers)
        try { stylesheet.insertRule(selector+' {'+property+':'+value+'}', stylesheet.cssRules.length);
        } catch(err) {try { stylesheet.addRule(selector, property+':'+value); // (pre IE9)
        } catch(err) {console.log("Couldn't add style");}} // (alien browsers)
    }
})(window);
非常容易实施。谢谢
2021-03-18 21:05:43
非常好的实现。向你致敬,先生。
2021-04-01 21:05:43
@ user21820,可能不是。我想我真的很想安全一点..答案终于更新了,向你致敬:)
2021-04-06 21:05:43
是否有理由修改每个样式表,而不是像我的回答那样只修改一个新创建的样式表?
2021-04-09 21:05:43

收集答案中的代码,我编写了这个在我的 FF 25 上运行良好的函数。

function CCSStylesheetRuleStyle(stylesheet, selectorText, style, value){
  /* returns the value of the element style of the rule in the stylesheet
  *  If no value is given, reads the value
  *  If value is given, the value is changed and returned
  *  If '' (empty string) is given, erases the value.
  *  The browser will apply the default one
  *
  * string stylesheet: part of the .css name to be recognized, e.g. 'default'
  * string selectorText: css selector, e.g. '#myId', '.myClass', 'thead td'
  * string style: camelCase element style, e.g. 'fontSize'
  * string value optionnal : the new value
  */
  var CCSstyle = undefined, rules;
  for(var m in document.styleSheets){
    if(document.styleSheets[m].href.indexOf(stylesheet) != -1){
     rules = document.styleSheets[m][document.all ? 'rules' : 'cssRules'];
     for(var n in rules){
       if(rules[n].selectorText == selectorText){
         CCSstyle = rules[n].style;
         break;
       }
     }
     break;
    }
  }
  if(value == undefined)
    return CCSstyle[style]
  else
    return CCSstyle[style] = value
}

这是一种将值放入 css 中的方法,即使浏览器不理解这些值也会在 JS 中使用。例如,滚动表中 tbody 的 maxHeight。

称呼 :

CCSStylesheetRuleStyle('default', "#mydiv", "height");

CCSStylesheetRuleStyle('default', "#mydiv", "color", "#EEE");

如果样式嵌入在 HTML 页面中,document.styleSheets[m].href则将为 null 并失败。
2021-03-30 21:05:43

我不知道为什么其他解决方案会遍历文档的整个样式表列表。这样做会在每个样式表中创建一个新条目,这是低效的。相反,我们可以简单地附加一个新的样式表并简单地在那里添加我们想要的 CSS 规则。

style=document.createElement('style');
document.head.appendChild(style);
stylesheet=style.sheet;
function css(selector,property,value)
{
    try{ stylesheet.insertRule(selector+' {'+property+':'+value+'}',stylesheet.cssRules.length); }
    catch(err){}
}

请注意,我们甚至可以通过将“!important”添加到属性值来覆盖直接在元素上设置的内联样式,除非该属性已经存在更具体的“!important”样式声明。

有关更复杂的版本,请参阅developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/ ...。
2021-04-05 21:05:43
非常真实。如果 .insertRule 失败,请务必使用 .addRule(selector, property+':'+value) (对于 IE9 之前的支持)。
2021-04-09 21:05:43

我没有足够的代表来发表评论,所以我会格式化一个答案,但这只是对相关问题的演示。

看起来,当在样式表中定义元素样式时,它们对 getElementById("someElement").style 不可见

这段代码说明了这个问题... jsFiddle 下面的代码

在测试 2 中,在第一次调用时,items left 值是未定义的,因此,应该是一个简单的切换的东西变得一团糟。对于我的使用,我将内联定义我的重要样式值,但它似乎在一定程度上违背了样式表的目的。

这是页面代码...

<html>
  <head>
    <style type="text/css">
      #test2a{
        position: absolute;
        left: 0px;
        width: 50px;
        height: 50px;
        background-color: green;
        border: 4px solid black;
      }
      #test2b{
        position: absolute;
        left: 55px;
        width: 50px;
        height: 50px;
        background-color: yellow;
        margin: 4px;
      }
    </style>
  </head>
  <body>

  <!-- test1 -->
    Swap left positions function with styles defined inline.
    <a href="javascript:test1();">Test 1</a><br>
    <div class="container">
      <div id="test1a" style="position: absolute;left: 0px;width: 50px; height: 50px;background-color: green;border: 4px solid black;"></div>
      <div id="test1b" style="position: absolute;left: 55px;width: 50px; height: 50px;background-color: yellow;margin: 4px;"></div>
    </div>
    <script type="text/javascript">
     function test1(){
       var a = document.getElementById("test1a");
       var b = document.getElementById("test1b");
       alert(a.style.left + " - " + b.style.left);
       a.style.left = (a.style.left == "0px")? "55px" : "0px";
       b.style.left = (b.style.left == "0px")? "55px" : "0px";
     }
    </script>
  <!-- end test 1 -->

  <!-- test2 -->
    <div id="moveDownThePage" style="position: relative;top: 70px;">
    Identical function with styles defined in stylesheet.
    <a href="javascript:test2();">Test 2</a><br>
    <div class="container">
      <div id="test2a"></div>
      <div id="test2b"></div>
    </div>
    </div>
    <script type="text/javascript">
     function test2(){
       var a = document.getElementById("test2a");
       var b = document.getElementById("test2b");
       alert(a.style.left + " - " + b.style.left);
       a.style.left = (a.style.left == "0px")? "55px" : "0px";
       b.style.left = (b.style.left == "0px")? "55px" : "0px";
     }
    </script>
  <!-- end test 2 -->

  </body>
</html>

我希望这有助于阐明这个问题。

跳过