簡體   English   中英

如何使主體具有與style =“ background-color:returnBlue()”相同的style屬性,其中returnBlue()返回“ blue”?

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

<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;")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM