首页 > 解决方案 > 使用 JavaScript 有效地应用样式(最佳实践?)

问题描述

我正在为 Greasemonkey/Tampermonkey 编写用户脚本(并在此过程中学习 JS)。它用于讨论论坛(/公告板),其中每个帖子都根据某些标准分配为六种可能的样式之一。帖子包含div用户名、div时间戳、div头像和用户信息,以及div内容本身(可能包含也可能不包含引用 div)。

为简单起见,我们只将样式称为redbluegreenyellow和。(注意:不仅仅是颜色——每种样式都有自己独特的“一切”值,甚至是边距、填充和其他布局。blackwhite

然后,每个帖子都通过调用样式更改函数来设置样式,例如makeRed(post)makeGreen(post)

然后,每个函数看起来像这样:

const makeRed = post => {
    let author = post.querySelector(".author");
    author.style.fontSize = "...";
    author.style.fontFamily = "...";
    author.style.backgroundColor = "...";
    author.style.padding = "...";
    author.style.borderRadius = "...";
    author.style.margin = "...";
    author.style.flex = "...";
    // ...

    let date = post.querySelector(".date");
    date.style.fontFamily = "...";
    date.style.fontSize = "...";
    date.style.color = "...";
    date.style.margin = "...";
    date.style.flex = "...";
    // ...

    let avatarInfo = post.querySelector(".infoBox");
    avatarInfo.style.backgroundColor = "...";
    avatarInfo.style.fontSize = "...";
    // ...

    let content = post.querySelector(".content");
    content.style.borderColor = "...";
    content.style.backgroundImage = "...";
    // ...

    let quote = content.querySelector(".quote");
    if (quote) {
        // Lots of quote styling here
    } else {
        // Lots of quote-less styling here
    }
}

这些函数中的每一个都以类似的方式包含更多的代码行,我只是将它们从这个问题中删除以节省一些空间。

所以,对于这个问题:
有没有办法更简洁/优雅地写这个?

我想很难避免为每个样式属性设置一行,但至少在 CSS 中它看起来更好一些,IMO。创建一个 CSS 文件并以某种方式使用 JavaScript 导入它会是一个更好的做法(如何?),还是这个长长的列表实际上是要走的路?或者,还有更好的方法?你会怎么做?element.style.property = "..."

另外,我是 JS 的新手,所以如果您有任何其他建议(是否与我的代码相关),请告诉我!
非常感谢!:-)

编辑:
我被要求包含 HTML 结构。一个典型的帖子就是这样的:

<div class="post">
  <div class="author">Author McAuthorson</div>
  <div class="date">2021.01.10 01:23</div>
  <div class="infoBox">
    <div class="avatar"><img src="..." /></div>
    <div class="userinfo">User info here</div>
  </div>
  <div class="content">
    <div class="quote">Some quote by some guy here</div>
    Some original text by McAuthorson here.
  </div>   
</div>

标签: javascriptcss

解决方案


一种方法是使用 CSS 注入并向您希望更改的元素添加/删除类。

这是一个例子

const makeRed = post => post.classList.add('red')

const css = `
 .red > .author {
    background: red;
    font-weight: bold;
 }
 .red > .date {
    font-weight: bold;
 }
`

// inject the style first
document.head.insertAdjacentHTML("beforeend", `<style>${css}</style>`)

// call the func. to add the class then
setTimeout(() => makeRed(document.querySelector("#test")), 1000)
<div class="post" id="test">
  <div class="author">Author McAuthorson</div>
  <div class="date">2021.01.10 01:23</div>
  <div class="infoBox">
    <div class="avatar"><img src="..." /></div>
    <div class="userinfo">User info here</div>
  </div>
  <div class="content">
    <div class="quote">Some quote by some guy here</div>
    Some original text by McAuthorson here.
  </div>
</div>


推荐阅读