中附加任何样式
我在html网页上创建了一个元素。我没有看到为什么样式无法正常工作。也许有人会非常友善,以指出我可能犯的任何错误。谢谢。
///HTML
<!DOCTYPE html>
<html>
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src= "projectJS.js"></script>
</body>
</html>
///JS
var elemH1 = document.createElement("h1");
elemH1.style.color = "red";
elemH1.style.fontFamily = "Tahoma";
elemH1.style.textAlign = "center";
document.write("<h1>Kent Butler</h1>");
var elemH2 = document.createElement("h2");
elemH2.style.fontFamily = "Garamond";
elemH2.style.color = "red";
elemH2.style.fontStyle = "italic";
elemH2.style.textAlign = "center";
document.write("<h2>WEB 115.0001</h2>");
我正在寻找样式的红色和指定字体系列的文字。谢谢。
您需要在元素上设置文本,然后将它们添加到文档中。Body
var elemH1 = document.createElement("h1");
elemH1.style.color = "red";
elemH1.style.fontFamily = "Tahoma";
elemH1.style.textAlign = "center";
elemH1.innerText = "Kent Butler";
document.body.appendChild(elemH1);
//document.write("<h1>Kent Butler</h1>");
var elemH2 = document.createElement("h2");
elemH2.style.fontFamily = "Garamond";
elemH2.style.color = "red";
elemH2.style.fontStyle = "italic";
elemH2.style.textAlign = "center";
//document.write("<h2>WEB 115.0001</h2>");
elemH2.innerText = "WEB 115.0001";
document.body.appendChild(elemH2);
问题是您正在创建元素并设置其属性,但实际上并未使用它们。相反,您正在创建一个全新的元素,而没有document.write("<h1>Kent Butler</h1>")
另外,您应该考虑将样式放在CSS文件中,而不是用JS进行硬编码。