尝试创建名为container
的自定义div,但我无法使样式生效,实际上第33-39行禁止第41行工作。我尝试了一切让container
div出现但没有运气。请帮助,谢谢。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en"><head>
</head>
<style>
body
{
background-repeat:repeat;
background-color: white;
}
#container
{
position: relative;
margin: 0 auto;
}
#p_1
{
font-style:italic;
font-size: 50px;
font-color: black;
}
#p_2
{
font-style:italic;
font-size: 50px;
font-color: black;
}
</style>
<script language = "JavaScript">
function initialize_container(container)
{
document.getElementById("p_1").innerHTML = "<p> output p1 </p>";
var CONTAINER_TAG = document.getElementById("container");
CONTAINER_TAG.setAttribute("style", "width: 100px;");
CONTAINER_TAG.setAttribute("style", "heigth: 100px;");
CONTAINER_TAG.setAttribute("style", "border: 2px solid;");
CONTAINER_TAG.setAttribute("style", "border-radius: 25px;");
CONTAINER_TAG.setAttribute("style", "border-style: solid;");
CONTAINER_TAG.setAttribute("style", "border-color: purple;");
document.getElementById("p_2").innerHTML = "<p> output p2 </p>";
}
</script>
<body onload = "initialize_container('container')">
<div id = "container">
<p id = "p_1"></p>
<p id = "p_2"></p>
</div>
</body>
</html>
答案 0 :(得分:3)
每次调用setAttribute
时,您都会覆盖样式属性。它不是添加剂。只需一次调用setAttribute
即可完成所有风格
尝试替换它:
CONTAINER_TAG.setAttribute("style", "width:" + 100 + "px;");
CONTAINER_TAG.setAttribute("style", "heigth:" + 100 + "px;");
CONTAINER_TAG.setAttribute("style", "border: 2px solid;");
CONTAINER_TAG.setAttribute("style", "border-radius: 25px;");
CONTAINER_TAG.setAttribute("style", "border-style: solid;");
CONTAINER_TAG.setAttribute("style", "border-color: purple;");
用这个:
CONTAINER_TAG.setAttribute("style", "width:100px;heigth:100px;border: 2px solid;border-radius:25px;border-style: solid;border-color: purple;");
也只是要求:
document.getElementById("p_1").innerHTML = "<p> output p1 </p>";
您确定要将p
元素放在p_1
元素中吗?也许你想要
document.getElementById("p_1").innerHTML = "output p1";
答案 1 :(得分:0)
不要反复设置属性,而是更改该元素的样式。
CONTAINER_TAG.style.width = "100px";
CONTAINER_TAG.style.heigth = "100px";
CONTAINER_TAG.style.border = "2px solid purple";
CONTAINER_TAG.style.borderRadius = "25px";
提示强>
我注意到的一件事是你在函数中传递div的id作为参数,所以
var CONTAINER_TAG = document.getElementById("container");
应为var CONTAINER_TAG = document.getElementById(container);
希望,这有助于......
答案 2 :(得分:0)
通过这个过程,您也可以为特定元素提供样式。
CONTAINER_TAG.style.width = "500px";
CONTAINER_TAG.style.height = "100px";
CONTAINER_TAG.style.border = "4px solid green";