2016-03-18 13 views
14

Come si ottengono e si impostano le proprietà personalizzate CSS (quelle con accesso allo var(…) nel foglio di stile) utilizzando JavaScript (semplice o jQuery)?Accesso a una proprietà personalizzata CSS (anche variabile CSS) tramite JavaScript

Ecco il mio tentativo senza successo: cliccando sui pulsanti cambia la solita font-weight proprietà, ma non la proprietà personalizzata --mycolor:

<html> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
    <style> 
    body { 
     --mycolor: yellow; 
     background-color: var(--mycolor); 
    } 
    </style> 
</head> 
<body> 

    <p>Let's try to make this text bold and the background red.</p> 
    <button onclick="plain_js()">Plain JS</button> 
    <button onclick="jQuery_()">jQuery</button> 

    <script> 
    function plain_js() { 
    document.body.style['font-weight'] = 'bold'; 
    document.body.style['--mycolor'] = 'red'; 
    }; 
    function jQuery_() { 
    $('body').css('font-weight', 'bold'); 
    $('body').css('--mycolor', 'red'); 
    } 
    </script> 
</body> 
</html> 
+0

'var' è supportato nei CSS? –

+3

@ Goth Sì, c'è. https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables È ancora sperimentale comunque. Inoltre, lo scopo non è inteso per le cose che si modificano in fase di esecuzione ma per la manutenibilità. Se vuoi cose che puoi cambiare guarda [attr] (https://developer.mozilla.org/en/docs/Web/CSS/attr) – ste2425

+0

Le variabili CSS sono una caratteristica sperimentale ... Non mi aspetterei che il essere ancora accessibile tramite JS. Potrei sbagliarmi ... Ma perché non usare FireBug e aspettarsi gli elementi DOM, per scoprire te stesso? – Connum

risposta

14

È possibile utilizzare document.body.style.setProperty('--name', value);:

var bodyStyles = window.getComputedStyle(document.body); 
var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get 

document.body.style.setProperty('--foo-bar', newValue);//set 

Ulteriori informazioni here.

+0

Il set aggiorna anche tutti i riferimenti a quella variabile nel CSS? – ste2425

+0

Può essere usato come variabile globale che può cambiare senza caricare un nuovo file. CSS – CMedina

+0

Per chiunque voglia ottenere o impostare una proprietà sul '' -tag invece del corpo: è possibile accedervi con 'document.documentElement '. – thutt

0

Il seguente esempio illustra come si può cambiare lo sfondo utilizzando JavaScript o jQuery, sfruttando le proprietà CSS personalizzate note anche come variabili CSS (maggiori informazioni here). Bonus: il codice indica anche come si può usare una variabile CSS per cambiare il colore del carattere.

function plain_js() { 
 
    // need DOM to set --mycolor to a different color 
 
    d.body.style.setProperty('--mycolor', 'red'); 
 
     
 
    // get the CSS variable ... 
 
    bodyStyles = window.getComputedStyle(document.body); 
 
    fontcolor = bodyStyles.getPropertyValue('--font-color'); //get 
 
    
 
    // ... reset body element to custom property's new value 
 
    d.body.style.color = fontcolor; 
 
    d.g("para").style["font-weight"] = "bold"; 
 
    this.style.display="none"; 
 
    }; 
 

 
    function jQuery_() { 
 
    $("body").get(0).style.setProperty('--mycolor','#f3f'); 
 
    $("body").css("color",fontcolor); 
 
    $("#para").css("fontWeight","bold"); 
 
    $(this).css("display","none"); 
 
    } 
 
    
 
var bodyStyles = null; 
 
var fontcolor = ""; 
 
var d = document; 
 

 
d.g = d.getElementById; 
 
d.g("red").addEventListener("click",plain_js); 
 
d.g("pink").addEventListener("click",jQuery_);
:root { 
 
    --font-color:white; 
 
    --mycolor:yellow; 
 
    } 
 
    body { 
 
     background-color: var(--mycolor); 
 
     color:#090; 
 
    } 
 
    
 
    #para { 
 
    font: 90% Arial,Helvetica; 
 
    font-weight:normal; 
 
    } 
 
    
 
    #red { 
 
     background:red; 
 
    } 
 
    
 
    #pink { 
 
     background:#f3f; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
 
<p id="para">Let's try to make the background red or pink and change the text to white and bold.</p> 
 
    <button id="red">Red</button> 
 
    <button id="pink">Pink</button>

Si noti che con jQuery, al fine di impostare la proprietà personalizzata per un valore differente, questo response in realtà vale la risposta. Utilizza il metodo get() dell'elemento body che consente l'accesso alla struttura DOM sottostante e restituisce l'elemento body, facilitando in tal modo il codice che imposta la proprietà personalizzata --mycolor su un nuovo valore.