【问题标题】:css style Replace inline one style namecss style 替换内联一种样式名称
【发布时间】:2019-01-02 17:59:35
【问题描述】:

我有内联样式 css 字符串,我只想替换一个样式名称。我想为所有样式名称制作通用正则表达式。 正则表达式:

/([a-z\-]+):\s*([a-z0-9]+);/mg

HTML:

<div style="top: auto; max-width:257px; left: 155px; right: auto; bottom: 88px; max-height: 313px; display: block;"></div>

结果(我想将max-width:257px; 替换为max-width:20px;):

<div style="top: auto; max-width:20px; left: 155px; right: auto; bottom: 88px; max-height: 313px; display: block;"></div>

问题是所有样式名都替换为max-width

<div style="max-width:20px; max-width:20px; max-width:20px; max-width:20px; max-width:20px; max-width:20px; max-width:20px;"></div>

https://regex101.com/r/5aHHZd/2

【问题讨论】:

    标签: javascript css regex replace styles


    【解决方案1】:

    有一个cssText API,可以一次性设置多个CSS属性。它的缺点是它替换了所有现有的样式。

    因此,通过创建一个微小的“自定义”setCSSText 函数,您可以做同样的事情,尽管现有的保持不变。

    堆栈sn-p

    var div = document.querySelector('div');
    
    setCSSText(div,"maxWidth:20px;color:red")
    
    function setCSSText(el,ss) {
      ss.split(';').forEach(function(s){
        var pv = s.split(':');
        if (pv.length > 1) {
          el.style[pv[0].trim()] = pv[1].trim();
        }
      })
    }
    &lt;div style="top: auto; max-width:257px; left: 155px; right: auto; bottom: 88px; max-height: 313px; display: block;"&gt;Some dummy text&lt;/div&gt;

    【讨论】:

      【解决方案2】:

      首先,您的问题自相矛盾。您说正则表达式适用于所有样式名称,但您只想更改特定的 CSS 属性。其次,我无法理解为什么你需要一个正则表达式来定位这个属性。您可以使用 CSS 和 JavaScript 选择此属性并将其更改为您想要的任何值。

      CSS:

      div{ max-width: 20px; }
      

      JS:

      document.getElementsByTagName("div")[0].style.maxWidth = "20px";
      

      编辑: 作为对您的评论的回应,我将看看 jQuery css() 方法。 https://www.w3schools.com/JQuery/jquery_css.asp 这基本上允许您设置任何 css 属性。

      【讨论】:

      • 但我需要通用函数,因为在参数中我采用color:red;min-height:30pxpadding: 100px; border: 1px solid black;。而且我必须编写一个函数来获取每个样式名称
      猜你喜欢
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 2015-10-02
      • 2016-06-01
      • 2013-06-26
      • 2014-09-25
      • 1970-01-01
      • 2014-06-27
      相关资源
      最近更新 更多