簡體   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