【问题标题】:Make style inline using jQuery使用 jQuery 使样式内联
【发布时间】:2011-09-26 21:12:25
【问题描述】:

我正在尝试设置一种自动方法,将基于干净样式表的设计转换为丑陋的内联样式设计(用于时事通讯编辑器)。

是否可以获取适用于元素的所有样式(div、p、span、h1、h2 等)并将它们作为内联应用到该元素?

所以不要在样式表中让我的风格像这样漂亮:

#topHeader { color: #222; background: red; width: 210px; height: 110px;}

像这样内联:

<div id="topHeader" style="color: #222; background: red; width: 210px; height: 110px;">

如果有人知道这是否可能,请尽可能向我发送正确的方向。

还是谢谢:)

【问题讨论】:

    标签: jquery css stylesheet inline styling


    【解决方案1】:

    你可能会感兴趣:

    【讨论】:

      【解决方案2】:

      您可以使用您所引用的 DOM 元素的 .style 成员来执行此操作。使用您的示例,可能是这些方面的内容(未经测试):

      var el     = document.getElementById('topHeader');
      var styles = new Array();
      
      for (var key in el.style) {
          // You'll probably need to do some more conditional work here...
          if (el.style[key]) {
              styles.push(key + ': ' + el.style[key]);
          }
      }
      
      el.setAttribute('style', styles.join('; '));
      

      【讨论】:

      • 有趣.. 将在今天晚些时候尝试。感谢您的快速回答!
      【解决方案3】:

      您可以迭代文档的样式表和规则:

      $.each(document.styleSheets, function() {
          $.each(this.cssRules || this.rules, function() {
              var style = {};
              var styles = this.cssText.split(/;\s*/g);
              $.each(styles, function() {
                  var parts = styles.split(/\:\s*/g);
                  style[parts[0]] = parts[1];
              });
              $(this.selectorText).css(style);
          });
      });
      

      并非所有浏览器都公开.selectorText,而.cssText 将需要特定于浏览器的解析。希望这足以为您指明正确的方向。

      【讨论】:

        【解决方案4】:

        我使用以下方法取得了一定的成功:

        $('#parentidhere').find('*').each(function (i, elem){elem.style.cssText=document.defaultView.getComputedStyle(elem,"").cssText;});
        

        某些样式(例如用于更复杂样式的背景选择器)似乎仍然消失了,但我还没有弄清楚原因。 这在旧浏览器中也不起作用,但在我的情况下这并不重要。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-09-24
          • 2013-03-25
          • 2011-01-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多