javascript正则表达式,用于编辑元素内部的css样式属性
javascript regular expression to edit css style attributes inside of an element
我正在编写一个javascript代码,它将操作/处理html内容,该内容具有内联css。我只需要对css内容进行更改。我有一个类似的html代码/字符串
<div style="height:20px;color:yellow;"> and some special characters here</div>
<div style="width: 200px;color:red;"><p style="font-size: 20px;">some content here ></p></div>
现在我想添加'!"important"标记到css参数,而不是到html特殊字符。结果应为
<div style="height:20px !important;color:yellow !important;"> and some special characters here</div>
<div style="width: 200px !important;color:red !important;"><p style="font-size: 20px !important;">some content here ></p></div>
这个的正则表达式是什么?我试过像这个
var str='<div style="height:20px;color:yellow;"> and some special characters here</div>
<div style="width: 200px;color:red;"><p style="font-size: 20px;">some content here ></p></div>'
var str2 = str.replace(';', ' !important;')
结果是
<div style="height:20px !important;color:yellow !important;">  !important; and some special characters here</div>
<div style="width: 200px !important;color:red !important;"><p style="font-size: 20px !important;">some content here > !important;</p></div>
我知道这不是正确的,因为它用"!importanr;"替换了所有分号(;)。如果有人能给我一个只改变风格内部内容的正则表达式,我将不胜感激
请注意,我不是在网页/DOM上做这件事的。提前谢谢。
Regex/(?=[^<>]+:|'s*")/g
用法
var str='<div style="height:20px;color:yellow;"> and some special characters here</div>
<div style="width: 200px;color:red;"><p style="font-size: 20px;">some content here ></p></div>'
var str2 = str.replace(/;(?=[^<>]+:|'s*")/g, ' !important;')
Fiddle
var divElements = document.querySelectorAll("div"); // reference of div
var regPattern = /(?:(.*?);)/gm; // regex
for(var i = 0, len = divElements.length; i< len; i++) {
var divElementCss = divElements[i].style.cssText; // getting the css alone
divElementCss = divElementCss.replace(regPattern, "$1 !important;");
// adding !important
divElements[i].style.cssText = divElementCss; // replace again
}
相关文章:
- 如果文本字段为空,则使用JavaScript应用CSS样式
- FF和Chromium中CSS样式按钮的外观差异
- CSS样式属性留空
- CKeditor预览插件.js,为Chrome和IE进行编辑.因为它拒绝CSS样式
- 基于路由的CSS样式-Angular2
- 为未标记的文本添加CSS样式
- 使用JQuery将现有CSS样式扩展%-%
- JavaScript-在keyDown上切换css样式
- React js应用程序's在托管应用程序中打开时将覆盖css样式
- 如何在javascript中更改段落中不同行的css样式
- 通过javascript设置IE特定的css样式
- PHP,MySQL,AJAX-调用AJAX结果后,Bootstrap CSS样式不会显示
- 使用javascript/jquery检查.css样式表的名称
- JavaScript和CSS样式不适用于我的“;谷歌网站”;页
- 未使用jQuery验证器选中Css样式复选框时
- javascript正则表达式,用于编辑元素内部的css样式属性
- css样式加载+id.例如加载1、加载300
- 无法在运行时将CSS样式添加到元素中
- d3js 通过其 CSS 样式选择所有元素
- 如何根据浏览器宽度动态调整 css 样式表