JS30 - 03 CSS Variables
效果展示
相关知识
-
document.documentElement === document.querySelector(':root') === document.querySelector('html')
-
style.setProperty(propertyName, value, priority); :为声明了 CSS 样式的对象设置一个新的值。
-
HTMLElement.dataset 属性:
- 访问在 HTML 或 DOM 中的元素上设置的所有自定义数据属性 (data-*) 集
- 详见:MDN: HTMLElement.dataset
代码展示
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scoped CSS Variables and JS</title>
</head>
<body>
<h2>Update CSS Variables with <span class='hl'>JS</span></h2>
<div class="controls">
<label for="spacing">Spacing:</label>
<input id="spacing" type="range" name="spacing" min="10" max="200" value="10" data-sizing="px">
<label for="blur">Blur:</label>
<input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px">
<label for="base">Base Color</label>
<input id="base" type="color" name="base" value="#ffc600">
</div>
<img src="img/haiou.jpg">
<style>
:root {
--base: #ffc600;
--spacing: 10px;
--blur: 10px;
}
img {
width: 500px;
padding: var(--spacing);
background: var(--base);
filter: blur(var(--blur));
}
.hl {
color: var(--base);
}
/*
misc styles, nothing to do with CSS variables
*/
body {
color: white;
font-family: 'helvetica neue', sans-serif;
font-weight: 100;
font-size: 50px;
text-align: center;
background: #193549;
}
.controls {
margin-bottom: 50px;
}
input {
width: 100px;
}
</style>
<script>
(function () {
function changeHandler () {
// document.documentElement === document.querySelector(':root') === document.querySelector('html')
document.querySelector(':root').style.setProperty(`--${this.name}`, this.value + (this.dataset.sizing || ''));
}
let inputs = document.querySelectorAll('.controls input');
inputs.forEach(function(input) {
input.addEventListener('change', changeHandler);
input.addEventListener('mousemove', changeHandler);
});
})();
</script>
</body>
</html>