[英]css style Replace inline one style name
我有內聯樣式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>
首先,您在自己的問題中自相矛盾。 您說正則表達式適用於所有樣式名稱,但是您只想更改特定的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屬性。
存在一個cssText API ,通過它可以一次設置多個CSS屬性。 它的缺點是它將替換所有現有樣式。
因此,通過創建一個微小的“自定義” setCSSText
函數,盡管可以保持現有狀態不變,但是您可以執行相同操作。
堆棧片段
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.