动态生成类规则并插入到样式表中

58 阅读1分钟
 /*
   * 动态生成类规则并插入到样式表中
   * @param {string} prefix - 类名前缀 (如: "mt-", "wt-")
   * @param {string} property - CSS 属性名 (如: "margin-top", "width")
 */
function applyDynamicStyles (prefix, property) {
    const elements = document.querySelectorAll(`[class*="${prefix}["]`);
    const styleElement = document.createElement('style');
    document.head.appendChild(styleElement);
    const styleSheet = styleElement.sheet;
    const addedClasses = new Set();

    elements.forEach(element => {
      const className = element.className;
      const regex = new RegExp(`${prefix}\\[(.*?)\\]`); // 动态匹配前缀和括号中的值
      const match = className.match(regex);

      if (match) {
        const value = match[1]; // 获取括号内的值
        const sanitizedValue = value.replace(/[^a-zA-Z0-9-]/g, ""); // 清理非法字符
        const dynamicClass = `${prefix}${sanitizedValue}`;

        if (!addedClasses.has(dynamicClass)) {
          // 插入动态规则
          styleSheet.insertRule(
            `.${dynamicClass} { ${property}: ${value}; }`,
            styleSheet.cssRules.length
          );
          addedClasses.add(dynamicClass);
        }

        // 替换原始类名为合法类
        element.classList.add(dynamicClass);
      }
    });
  }

  // 页面加载完成后执行
  document.addEventListener("DOMContentLoaded", () => {
    applyDynamicStyles("mt-", "margin-top");
    applyDynamicStyles("mb-", "margin-bottom");
    applyDynamicStyles("mr-", "margin-right");
    applyDynamicStyles("wt-", "width");
    applyDynamicStyles("ht-", "height");
    applyDynamicStyles("b-r-", "border-radius");
  });
  
 用法
 <div class="mt-[60px] wt-[1400px] ht-[820px]">