2016-08-22 49 views
2

本週我發現了CSS3變量的榮耀!愛他們!使用JavaScript獲取和設置CSS變量?

:root { 
    --main-height: 45px; 
    --main-gutter: -8px; 

    --match-width: 180px; 
    --player-width: 370px; 
    --score-width: 60px; 
} 

我的問題......有沒有一種方法可以在JavaScript中設置/設置這些變量?

+0

http://stackoverflow.com/questions/8742249/how-to-set-css3-transition-使用-javascript –

+0

請注意IE可能不支持CSS3變量。 – Scott

+0

不要害怕就這麼說:IE *不支持此功能。它永遠不會。 – BoltClock

回答

2

這裏有一個工作演示CODEPEN和下面的代碼段。詳細信息在源代碼中進行了評論。

的關鍵部分是:

setPropertytemplate literals

// Collect the inputs 
 
const adjGrp = [].slice.call(document.querySelectorAll('#adjustments input')); 
 

 
// Add an eventListener to each input for the change event 
 
adjGrp.forEach(input => input.addEventListener('change', adjCSS)); 
 

 
// Event handler uses setProperty method and template literal of the CSS variable 
 
// Input name attributes are referenced to the corresponding CSS variable 
 
function adjCSS(e) { 
 
    document.documentElement.style.setProperty(`--${this.name}`, this.value + 'px'); 
 
}
:root { 
 
    --mainh: 45px; 
 
    --mainw: 480px; 
 
    --match: 180px; 
 
    --player: 370px; 
 
    --score: 60px; 
 
} 
 
#main { 
 
    font: 500 16px/1.5 Consolas; 
 
    height: var(--mainh); 
 
    width: var(--mainw); 
 
} 
 
#scoreboard { 
 
    display: table; 
 
    width: calc(var(--player) + 150px); 
 
    height: calc((var(--main) * .2)); 
 
    margin: 15px 0 15px 20px; 
 
} 
 
legend { 
 
    font-size: 1.6rem; 
 
    font-variant: small-caps; 
 
} 
 
output { 
 
    display: table-cell; 
 
    line-height: 1.5; 
 
    border: 3px inset grey; 
 
    padding: 3px 5px; 
 
} 
 
#match { 
 
    width: var(--match); 
 
} 
 
#player { 
 
    width: var(--player); 
 
} 
 
#score { 
 
    width: var(--score); 
 
} 
 
#adjustments { 
 
    margin: 0 0 0 20px; 
 
}
<form id='main'> 
 
    <fieldset id='scoreboard'> 
 
    <legend>Scoreboard</legend> 
 
    <input id='m' type='hidden'> 
 
    <input id='p' type='hidden'> 
 
    <input id='s' type='hidden'> 
 

 
    <label>Player 
 
     <output id='player' for='p'>Name</output> 
 
     <br/> 
 
    </label> 
 
    <label>Match&nbsp; 
 
     <output id='match' for='m'>0</output> 
 
     <br/> 
 
    </label> 
 
    <label>Score&nbsp; 
 
     <output id='score' for='s'>0</output> 
 
    </label> 
 
    </fieldset> 
 

 

 
    <fieldset id='adjustments'> 
 
    <legend>Adjustments</legend> 
 
    <label>Player 
 
     <input name='player' type='number'> 
 
    </label> 
 
    <br/> 
 
    <label>Match&nbsp; 
 
     <input name='match' type='number'> 
 
    </label> 
 
    <br/> 
 
    <label>Score&nbsp; 
 
     <input name='score' type='number'> 
 
    </label> 
 
    <br/> 
 
    </fieldset> 
 
</form>

0

您可以創建一個樣式元素,並將其附加到包含您想要的任何CSS的<head>

$("head").append(` 
    <style type="text/css"> 
    CSS CODE 
    </style> 
`); 

雖然如果您關心跨瀏覽器兼容性,您可能不應該使用CSS變量。