-2

到目前为止,我发现了非常复杂的信息。如何使用 JavaScript 将这些 CSS 元素简单地添加到同一个 HTML 文件中?非常感谢您!

body {
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    font-size: 1.6rem;
    padding: 1rem;
}

ul {
    list-style-type: disc;
    padding: 1rem 1rem 1rem 4rem;
    list-style: 1.5;
    list-style-position: inside;
}

h1 {
    font-size: 24px;
    color: rgb(247, 34, 211);
    padding-bottom: 2rem;
}

h2 {
    font-size: 2.4rem;
    margin-bottom: 1rem;
}
4

3 回答 3

2

您可以创建一个类,如:

.bodystyle {
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    font-size: 1.6rem;
    padding: 1rem;
}

并将其与 js 一起添加到您的 body 元素中:

document.querySelector("body").classList.add("bodystyle")
于 2021-10-26T07:19:33.523 回答
0

我猜你必须在javascript中使用属性样式:

document.getElementById("myH1").style.color = "red";

或在 HTML 中添加样式页面:

<head>
<title>
    Load CSS file using JavaScript
</title>

<script>
  
    // Create new link Element
    var link = document.createElement('link'); 

    // set the attributes for link element
       link.rel = 'stylesheet'; 
  
    link.type = 'text/css';
  
    link.href = 'style.css'; 

    // Get HTML head element to append 
    // link element to it 
    document.getElementsByTagName('HEAD')[0].appendChild(link); 

</script> 

您可以使用此链接获取更多信息

于 2021-10-26T07:27:54.287 回答
0

听起来好像您想做的是将样式表添加到当前 HTML 的头部。

这就像在现有 HTML 中添加任何其他元素一样。创建一个样式元素,将您想要的 CSS 放入其中,将样式元素添加到 HTML 中的头部元素。

显然,要查看运行此代码段的效果,您必须查看浏览器的开发工具检查工具,以查看新样式表已添加到 head 元素的末尾。

const stylesheet = document.createElement('style');
stylesheet.innerHTML = `body {
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    font-size: 1.6rem;
    padding: 1rem;
}

ul {
    list-style-type: disc;
    padding: 1rem 1rem 1rem 4rem;
    list-style: 1.5;
    list-style-position: inside;
}

h1 {
    font-size: 24px;
    color: rgb(247, 34, 211);
    padding-bottom: 2rem;
}



h2 {
    font-size: 2.4rem;
    margin-bottom: 1rem;
}`;
document.querySelector('head').appendChild(stylesheet);
<!doctype html>
<html>

<head>
</head>

<body>
</body>

</html>

于 2021-10-26T07:50:12.273 回答