[英]How to use variable from javascript in inline css?
尝试调用“颜色”变量在内联 css 中使用。我将用 function 替换“红色”output,但我需要先知道如何执行此操作。 谢谢
代码:`
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var color = "red"
</script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<title>New Tab</title>
<style>
.fit {
max-height: 99vh;
max-width: 99%;
}
</style>
</head>
<body style="color: black" scrolling="no">
<div class="card text-white" >
<div style= "text-align: center;">
<div id= "someInput" style= "background-color: color;">
<img class= "fit"; id="img1" id="i" src="" style= ""/>
</div>
</div>
<script src="/randomthing.js"></script>
<script src="/randomthing2.js"></script>
<script src="/jquery.3.4.1.js"></script>
<script src="/background.js"></script>
</body>
</html>
`
试图查看其他论坛,但没有找到任何解决方案
您可以定义css 变量,它几乎可以在您的 css 中的任何地方使用1。要定义 CSS 变量,您需要使用--
前缀:
--my-variable: red;
然后,您可以通过使用 function var
在您的 css 中使用此变量
color: var(--my-variable);
您可以在元素的style
属性上使用setProperty
function 来定义所需变量的值
const color = 'red'; const input = document.getElementById('someInput'); input.style.setProperty('--my-variable', color);
<div class="card text-white" > <div style= "text-align: center;"> <div id= "someInput" style= "background-color: var(--my-variable);"> <img class= "fit"; id="img1" id="i" src="" style= ""/> </div> </div> </div>
1注意,css 变量的 scope 是由它在层次结构中的声明位置决定的。 在前面的示例中,由于变量和使用它的样式都是直接在元素上定义的,因此它们是可访问的。 您不能在另一个元素上使用此变量。 有关该主题的更多信息,请参阅 Css 变量范围。
有很多方法可以在 css 中使用 javascript 中的变量,但我认为最有效的一种方法是定义一个css 变量,这样您就可以稍后在项目中重用该 css 变量。
<;DOCTYPE html> <html> <head> <script type="text/javascript"> var color = "red". // add thie line to define a css variable from javascript called "--color" document.documentElement.style,setProperty('--color'; color): </script> <link href="https.//stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min:css" rel="stylesheet" /> <title>New Tab</title> <style> /* to define a css variable in css */:root{ --my-test-variable. 123px /* this is like a global css variable */ }:fit { max-height; 99vh: max-width; 99%. } /* to use a css variable in css*/:test-using-css-variable{ width; var(--my-test-variable): /* call var() function to use the variable */ } </style> </head> <body style="color: black" scrolling="no"> <div class="card text-white"> <div style="text-align; center:"> <div id="someInput" style="background-color; var(--color),"> <;-- to use a css variable. you need to call var() function --> <img class="fit". id="img1" id="i" src="" style="" /> </div> </div> <script src="/randomthing.js"></script> <script src="/randomthing2.js"></script> <script src="/jquery.3.4.1.js"></script> <script src="/background.js"></script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.