我想通过javascript更改元素的样式,但我的代码似乎不起作用。有什么帮助吗?
document.getElementById("box").style.background = #00ff00;
#box {
background: #ff00ff;
width: 100px;
height: 100px;
}
<html>
<body>
<div id="box"></div>
</body>
</html>
答案 0 :(得分:2)
您需要围绕颜色的引号。
document.getElementById("box").style.background = "#00ff00";
您可以在此处看到它:https://jsfiddle.net/royq5og0/
此外,如果您在浏览器中打开开发人员工具(F12),它将显示原始代码的错误。
希望有所帮助!
答案 1 :(得分:0)
你只是在颜色周围缺少引号:
document.getElementById("box").style.background = "#00ff00";
&#13;
#box {
background: #ff00ff;
width: 100px;
height: 100px;
}
&#13;
<div id="box"></div>
&#13;
答案 2 :(得分:0)
以下代码可用于更改javascript中的宽度
document.getElementById('box').style.width = '10px';
或者您可以使用setAttribute进行申请,使用此方法您可以一次应用多种样式,例如宽度,高度等。
document.getElementById('box').setAttribute("style", "width: 10px");
或者您也可以使用cssText,在单个语句中应用多种样式
document.getElementById("box").style.cssText = "width:10px;height:10px"
答案 3 :(得分:0)
使用任何颜色代码(如RGB,Hex等)时添加引号。
document.getElementById("box").style.background = '#00ff00';
或使用JQuery,你可以这样做:
$("#box").css("background-color","#00ff00");
这是一个通过JQuery更改CSS内容的有用链接,这很方便,因为选择更容易:http://www.w3schools.com/jquery/jquery_css.asp
希望这一切都有所帮助。