如何使主体采用等同于 style=“background-color: returnBlue()” 的样式属性,其中 r

How can I make the body take a style attribute equating to style="background-color: returnBlue()", where returnBlue() returns "blue"?

本文关键字:样式 属性 其中 returnBlue 主体 何使 等同于 style background-color      更新时间:2023-09-26
<html>
  <body style="background-color: returnBlue()">
    <em>Boy, I sure do wish I existed on something that was blue.</em>
  </body>
</html>

风格不会使身体变成蓝色

function returnBlue()
{
   return 'blue';
}

如何使returnBlue()函数运行并返回到属性?谢谢!

简而言之,你不能。style 属性被解析为 CSS,你尝试执行的是一个 JavaScript 函数。没有办法从CSS调用JS。

您可以做的是在脚本中获取对该元素的引用并手动更改它。

var body = document.body;
body.style.backgroundColor = returnBlue();

但是,与其尝试使用 JavaScript 手动设置节点样式,不如在 CSS 类中定义样式。

/* style.css */
.blue-bg {
  background-color: blue;
}

然后在 <body> 标记上使用该类。

<!-- index.html -->
<head>
  <link rel="stylesheet" href="style.css" />
</head>
<body class="blue-bg"></body>

如果你真的想以编程方式派生你的风格,那么你最好看看像SCSS这样支持函数的语言。

你不能在 CSS 中做到这一点,你只能用 JS 来做。

document.body.style.backgroundColor = returnBlue();

另外,当您尝试将其设置为蓝色时,为什么要使用returnBlue();?如果您想使用 JS 更改背景颜色,只需做

document.body.style.backgroundColor = color;

更新:如果你愿意,你可以使用 JQuery 的 .css(( 方法并执行$("body").css("background-color: blue;")