今週私はCSS3変数の栄光を発見しました!彼らを愛する!JavaScriptを使用したCSS変数の取得と設定
:root {
--main-height: 45px;
--main-gutter: -8px;
--match-width: 180px;
--player-width: 370px;
--score-width: 60px;
}
私の質問... JavaScriptでこれらの変数を取得/設定する方法はありますか?
今週私はCSS3変数の栄光を発見しました!彼らを愛する!JavaScriptを使用したCSS変数の取得と設定
:root {
--main-height: 45px;
--main-gutter: -8px;
--match-width: 180px;
--player-width: 370px;
--score-width: 60px;
}
私の質問... JavaScriptでこれらの変数を取得/設定する方法はありますか?
ここにデモがありますCODEPENと以下のスニペットがあります。詳細はソースでコメントされています。
重要な部分は、以下のとおりです。
// 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
<output id='match' for='m'>0</output>
<br/>
</label>
<label>Score
<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
<input name='match' type='number'>
</label>
<br/>
<label>Score
<input name='score' type='number'>
</label>
<br/>
</fieldset>
</form>
おそらくスタイルエレメントを作成し、それをあなたが望むCSSを含む<head>
に追加することができます。
$("head").append(`
<style type="text/css">
CSS CODE
</style>
`);
ブラウザ間の互換性を気にする人は、おそらくCSS変数を使用しないでください。
http://stackoverflow.com/questions/8742249/how-to-set-css3-transition- using-javascript –
IEがCSS3変数をサポートしていない可能性があることに注意してください。 – Scott
ちょうどそれを言うことを恐れてはいけません:IE *はこの機能をサポートしていません。それは決してできません。 – BoltClock