javascript - 如何通过 Javascript 获取自定义 css 样式?
问题描述
我想通过写课程来获得风格。
- 如果我写一个类名“mt-9”,那么它将添加margin-top: 9px; .
- 如果我写“mt-13”,那么它将添加margin-top: 13px;
- 如果我写“mtm-12”,那么它将为我添加margin-top: -12px;。
我希望通过纯JavaScript (Not jQuery)进行这种操作。我尝试了很多但失败了。任何人都可以让我知道这个js代码吗?
解决方案
试试这个:
const options = {
matchRegex: new RegExp('[m][-][t|l|b|r][-][0-9]+'),
'm-t': {
styleName: 'margin-top',
affix: 'px',
prefix: ''
},
'm-l': {
styleName: 'margin-left',
affix: 'px',
prefix: ''
},
'm-b': {
styleName: 'margin-bottom',
affix: 'px',
prefix: ''
},
'm-r': {
styleName: 'margin-right',
affix: 'px',
prefix: ''
}
}
document.querySelectorAll("*").forEach((e) => {
e.classList.forEach((classname) => {
if (options.matchRegex.test(classname)) {
const li = classname.lastIndexOf('-');
const type = classname.substring(0, li);
const value = classname.substring(li + 1);
const details = options[type];
e.style[details.styleName] = details.prefix + value + details.affix;
}
})
})
<div class="m-t-50 m-b-50">
Margin Top 50, Margin Bottom 50
</div>
<div class="m-t-10 m-l-20">
Margin Top 10, Margin Left 20
</div>
推荐阅读
- java - 如何在androidstudio中居中菜单项
- scala - 如何有效地删除 Scala 中的 var
- sql-server - 我们可以在 SQL SERVER 的非聚集索引的包含列列表中包含 UDT 吗?
- java - 无法在 Eclipse 中完成安装 WebSphere
- r - 根据季节开始和结束计算每像素平均降雨量值
- javascript - javascript if 语句因 ejs 失败
- python - 绘制networkx图时出现意外错误
- javascript - 带有等式的 HTML 弹出窗口
- mysql - 可以通过一个查询完成吗?MySQL只有一张表
- r - 如何以递增的方式拆分文本?