简体   繁体   English

CSS样式替换内联一个样式名称

[英]css style Replace inline one style name

I have inline style css string and I want replace only one style name. 我有内联样式CSS字符串,我只想替换一个样式名称。 I would like make universal regex for all style names. 我想为所有样式名称都使用通用正则表达式。 REGEX: 正则表达式:

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

HTML: HTML:

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

Result (I want replace max-width:257px; to max-width:20px; ): 结果(我想将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>

The problem is that all style names is replaced to max-width : 问题是所有样式名称都替换为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 https://regex101.com/r/5aHHZd/2

First of all, you contradict yourself in your question. 首先,您在自己的问题中自相矛盾。 You say that the regex is for all style names but you only want to change a specific CSS property. 您说正则表达式适用于所有样式名称,但是您只想更改特定的CSS属性。 Secondly, I can't possibly fathom why you need a regular expression to target this property. 其次,我无法理解为什么您需要使用正则表达式来定位此属性。 You can select this property using CSS and JavaScript and change it to whatever value you want. 您可以使用CSS和JavaScript选择此属性,并将其更改为所需的任何值。

CSS: CSS:

div{ max-width: 20px; }

JS: JS:

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

EDIT: IN response to your comment, I would take a look at the jQuery css() method. 编辑:作为对您的评论的回应,我将看一下jQuery css()方法。 https://www.w3schools.com/JQuery/jquery_css.asp This basically allows you to set any css property. https://www.w3schools.com/JQuery/jquery_css.asp这基本上允许您设置任何CSS属性。

There exists a cssText API , with which one can set several CSS properties in one go. 存在一个cssText API ,通过它可以一次设置多个CSS属性。 Its downside is that it replace all the existing styles. 它的缺点是它将替换所有现有样式。

So by create a tiny "custom" setCSSText function, you can do the same, though with the existing kept untouched. 因此,通过创建一个微小的“自定义” setCSSText函数,尽管可以保持现有状态不变,但是您可以执行相同操作。

Stack snippet 堆栈片段

 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(); } }) } 
 <div style="top: auto; max-width:257px; left: 155px; right: auto; bottom: 88px; max-height: 313px; display: block;">Some dummy text</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM