首页 > 解决方案 > 如何通过 Javascript 获取自定义 css 样式?

问题描述

我想通过写课程来获得风格。

我希望通过纯JavaScript (Not jQuery)进行这种操作。我尝试了很多但失败了。任何人都可以让我知道这个js代码吗?

标签: javascripthtmlcss

解决方案


试试这个:

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>


推荐阅读