简体   繁体   English

如何在没有内联样式的情况下将 CSS 应用于动态 JS 元素

[英]How to Apply CSS to Dynamic JS Elements without In-line Styling

I'm new to web development and I've been trying to apply styling to div elements that are generated using javascript, but I've only been able to do this manually using the following function:我是 web 开发的新手,我一直在尝试将样式应用于使用 javascript 生成的 div 元素,但我只能使用以下 ZC1C425268E68385D1AB5074C17A94F 手动执行此操作:

function addStyle(element) {
   rem = element.style;

   rem.fontSize = "16px"; 
   rem.background = "#fff"; 
   rem.color = "#333";
}

This works fine for individual elements, but there might be potentially dozens of dynamic elements created which all must include the same inline styling.这适用于单个元素,但可能会创建数十个动态元素,它们都必须包含相同的内联样式。 I've read elsewhere that apparently this is not a good practice and should be avoided if possible.我在其他地方读到过,显然这不是一个好习惯,如果可能的话应该避免。 Thus, I would prefer that these css rules are defined in a separate file so that I can potentially access them for other elements as well.因此,我希望这些 css 规则在单独的文件中定义,以便我也可以访问它们以获取其他元素。
However, I have been unable to find a solution anywhere online no matter how similar their issue may seem.但是,无论他们的问题看起来多么相似,我都无法在网上的任何地方找到解决方案。 Here's my relevant HTML code:这是我的相关 HTML 代码:

<h3 id="kudos_title">Kudos</h3>
<div class="remarks"></div>

My JS to create new div element:我的 JS 创建新的 div 元素:

function addElement (i) {
        // create a new div element
        const newDiv = document.createElement("div");

        // Add message, author, and source to content
        const content = document.createTextNode('"' + `${msg[i].remark}` + '"' + " - " + `${msg[i].author}` + " from " + `${msg[i].source}`);
        
        // add the text node to the newly created div
        newDiv.appendChild(content);

        addStyle(newDiv, i);

        // add the newly created element and its content into the DOM
        const current_remark = document.querySelector(".remarks");

        document.body.insertBefore(newDiv, current_remark);
        
    }

Lastly, the CSS:最后,CSS:

#kudos_title {
    text-align: center;
    font-family: Spectral, serif;
    font-size: 50px;
}

.remarks {
    padding: 20px;
    color: pink;
    background-color: springgreen;
}

I should mention that the heading with id=kudos_title is successfully styled, but anything part of the remarks class is not.我应该提到 id=kudos_title 的标题已成功设置样式,但 class 备注的任何部分都没有。 So clearly the.css file is being recognized for static elements, but JS created divs are not.很明显,.css 文件被 static 元素识别,但 JS 创建的 div 不是。

You are using insertBefore which will insert the element before the target (thus NOT inserting inside it).您正在使用insertBefore它将在目标之前插入元素(因此不会插入其中)。 Tryappending instead.尝试追加 Additionally, it's best practice to use HTML entities for things like quotes in text, so I used them here, showing how you can combine your string using your template literals.此外,最好将 HTML 实体用于文本中的引号等内容,因此我在这里使用了它们,展示了如何使用模板文字组合字符串。 To add certain classes, use element.classList.add()要添加某些类,请使用element.classList.add()

 let msg = [{ remark: "test", author: "they", source: "there" }]; function addElement(i) { // create a new div element const newDiv = document.createElement("div"); // Add message, author, and source to content const content = `&quot;${msg[i].remark}&quot; - ${msg[i].author} from ${msg[i].source}`; // add the text node to the newly created div newDiv.innerHTML = content; newDiv.classList.add('special'); // add the newly created element and its content into the DOM const current_remark = document.querySelector(".remarks"); current_remark.append(newDiv); } addElement(0);
 #kudos_title { text-align: center; font-family: Spectral, serif; font-size: 50px; }.remarks { padding: 20px; color: pink; background-color: springgreen; }.special { color: #f00; font-weight: bold; }
 <h3 id="kudos_title">Kudos</h3> <div class="remarks"></div>

If you want all the new divs to be styled in the same way, you can just give them a class and then define those styles in a CSS file.如果您希望所有新 div 都以相同的方式设置样式,您可以只给它们一个 class,然后在 CSS 文件中定义这些 styles。

You can do it like this: note that the name "myclass" is given purely for illustration, I'm sure you can come up with a meaningful name that works for your application:您可以这样做:请注意,名称“myclass”纯粹是为了说明,我相信您可以想出一个适用于您的应用程序的有意义的名称:

JS JS

function addElement (i) {
    // create a new div element
    const newDiv = document.createElement("div");

    // Add message, author, and source to content
    const content = document.createTextNode('"' + `${msg[i].remark}` + '"' + " - " + `${msg[i].author}` + " from " + `${msg[i].source}`);
    
    // add the text node to the newly created div
    newDiv.appendChild(content);

    // add CSS class
    newDiv.classList.append("myclass");

    // add the newly created element and its content into the DOM
    const current_remark = document.querySelector(".remarks");

    document.body.insertBefore(newDiv, current_remark);
    
}

CSS CSS

.myclass {
  font-size: 16px; 
  background: #fff"; 
  color: #333;
}

Just use a class and include it when making the element只需使用 class 并在制作元素时包含它

JS: JS:

newDiv.className = 'bar';

CSS: CSS:

.dynamicElement{
 padding: 20px;
    color: pink;
    background-color: springgreen;
}

You can just use a css file您可以只使用 css 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM