【问题标题】:Changing CSS Values with Javascript使用 Javascript 更改 CSS 值
【发布时间】:2010-10-08 15:34:03
【问题描述】:

使用 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%,而不是特定值),当我期望字符串时返回 Null “50%”并没有真正起作用。

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

【问题讨论】:

  • 你能编辑你的帖子吗?开头有一些不完整的句子,不知道你在找什么...
  • 我仍然对您的要求感到有些困惑。您是否要求 1) 更改 CSS 本身,这将立即更改所有元素?或 2) 一次更改单个项目的 CSS?
  • 我也很困惑,至于实际问题。对象的当前样式不一定与标签的“样式”属性相同。
  • 抱歉,我将对其进行编辑以使其更清晰。我不想设置内联 CSS。我希望能够增加/减少样式的宽度。我将用我正在寻找的完整示例进行编辑。

标签: javascript html css ajax dom


【解决方案1】:

也许试试这个:

function CCSStylesheetRuleStyle(stylesheet, selectorText, style, 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
}

【讨论】:

    【解决方案2】:

    我从未见过任何实际用途,但您可能应该考虑DOM stylesheets。但是,老实说,我认为这有点矫枉过正。

    如果您只是想获取元素的宽度和高度,无论从何处应用尺寸,只需使用element.offsetWidthelement.offsetHeight

    【讨论】:

    • 我的使用:
      增加会检查宽度是否
    【解决方案3】:

    This simple 32 lines gist 可让您识别给定的样式表并非常轻松地更改其样式:

    var styleSheet = StyleChanger("my_custom_identifier");
    styleSheet.change("darkolivegreen", "blue");
    

    【讨论】:

      【解决方案4】:

      请!只要问 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);
      

      【讨论】:

      • 非常容易实现。谢谢
      • 是否有理由修改每一个样式表,而不是像我的回答那样只修改一个新创建的样式表?
      • 非常好的实现。向您致敬,先生。
      • @user21820,可能不是。我想我真的很想保持安全。答案终于更新了,向你致敬:)
      【解决方案5】:

      我不知道为什么其他解决方案会遍历文档的整个样式表列表。这样做会在每个样式表中创建一个新条目,这是低效的。相反,我们可以简单地附加一个新样式表,然后在其中添加我们想要的 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”样式声明。

      【讨论】:

      【解决方案6】:

      收集答案中的代码,我编写了这个似乎在我的 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 并失败。
      【解决方案7】:

      好的,听起来您想更改全局 CSS,以便一次有效地更改特定样式的所有元素。我最近从Shawn Olson tutorial 学会了如何自己做这件事。可以直接参考他的代码here

      总结如下:

      您可以通过document.styleSheets 检索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.
      

      让我知道这对您有什么作用,如果您发现任何错误,请发表评论。

      【讨论】:

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

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

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

      这段代码说明了这个问题...Code from below on 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>
      

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

      跳过

      【讨论】:

        【解决方案9】:

        您可以获得任何元素的“计算”样式。

        IE 使用“currentStyle”,Firefox(我假设其他“符合标准”的浏览器)使用“defaultView.getComputedStyle”。

        您需要编写一个跨浏览器函数来执行此操作,或使用良好的 Javascript 框架,如原型或 jQuery(在原型 javascript 文件中搜索“getStyle”,在 jquery javascript 文件中搜索“curCss”)。

        也就是说,如果您需要高度或宽度,您可能应该使用 element.offsetHeight 和 element.offsetWidth。

        返回的值是 Null,所以如果我有 Javascript 需要知道某物的宽度来执行某些逻辑(我将宽度增加 1%,而不是特定值)

        请注意,如果您向相关元素添加内联样式,它可以充当“默认”值,并且在页面加载时可由 Javascript 读取,因为它是元素的内联样式属性:

        <div style="width:50%">....</div>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-03-22
          • 1970-01-01
          • 1970-01-01
          • 2012-09-17
          • 1970-01-01
          • 2018-12-12
          • 1970-01-01
          相关资源
          最近更新 更多