通过 JS 编辑 CSS

Editing CSS through JS

本文关键字:CSS 编辑 JS 通过      更新时间:2023-09-26

我想通过javascript更改元素的样式,但我的代码似乎不起作用。有什么帮助吗?

document.getElementById("box").style.background = #00ff00;
#box {
  background: #ff00ff;
  width: 100px;
  height: 100px;
}
<html>
<body>
  <div id="box"></div>
</body>
</html>

您需要在颜色周围加上引号。

document.getElementById("box").style.background = "#00ff00";

您可以在此处看到它的工作原理:https://jsfiddle.net/royq5og0/

此外,如果您在浏览器中打开开发人员工具(F12),它将显示原始代码的错误。

希望对您有所帮助!

您只是在颜色周围缺少引号:

document.getElementById("box").style.background = "#00ff00";
#box {
  background: #ff00ff;
  width: 100px;
  height: 100px;
}
<div id="box"></div>

下面的代码可以用来改变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"

使用任何颜色代码(如 RGB、十六进制等)时添加引号。

document.getElementById("box").style.background = '#00ff00';

或者使用 JQuery,您可以执行以下操作:

$("#box").css("background-color","#00ff00");

这是一个通过JQuery更改CSS内容的有用链接,它既好又方便,因为选择要容易得多:http://www.w3schools.com/jquery/jquery_css.asp

希望这一切都有帮助。