繁体   English   中英

如何在CSS中使用全局javascript变量?

[英]How to use a global javascript variable inside css?

我正在一个asp.net mvc应用程序上。 我需要知道如何在html代码中使用全局javascript变量。 我知道全局变量不是解决问题的理想解决方案,但是要使解决方案正常工作,我需要它们。

我知道他们的声明。 这是我要如何使用它们的示例。 我想使用全局js变量在输入中已经填写。

 var title; function foo(b) { title = b; }; 
 <input type="text" value=title readonly> 

任何帮助将不胜感激。 谢谢。

 var title; function foo(b) { document.getElementById("title").value = b; }; foo("irin") 
 <input type="text" id="title" readonly> 

使用任何HTMLElement对象的style对象的setProperty函数

 "use strict"; // Note the double quotation '" and "' // I won't work without, if you want to use the value // with CSS content rule const title = '"My title"'; document.getElementById('title').style.setProperty('--title', title); 
 div { padding: 5px; border: 1px solid gold; } div:before { content: var(--title, 'not set'); } 
 <div id="title"></div> 

在上面的示例中,我使用了[CSS custom Property][1] ,但是您可以不用

 "use strict"; const title = '"My title"'; const style = document.createElement('style'); style.textContent = `#title:before { content: ${title}; }`; document.head.append(style); 
 div { padding: 5px; border: 1px solid gold; } 
 <div id="title"></div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM