Web/CSS
[days05] CSS 전역변수와 document.querySelector
다연
2020. 12. 9. 19:18
반응형
전역변수
:root선택자 사용 -> var() 함수를 통해 사용 가능하다.
선언예시
<style>
:root{
/* --변수명:값; */
--blue:#1E90FF;
--white: #fff;
}
<style> 내에서 사용 예시
body{
background: var(--blue);
}
자바스크립트에서 사용할 때
var r = document.querySelector(":root");
var rs = getComputedStyle(r);
//getComputedStyle(r); - root로부터 스타일(속성명, 값들)을 얻어오는 함수
<script>
function getVariable() {
/* :root 선택자 */
//document.getElementById(id) 이렇게 가져올게 아니라
var r = document.querySelector(":root");
var rs = getComputedStyle(r); //암기
window.alert( rs.getPropertyValue('--blue') );
}
function setVariable() {
var color = document.getElementById("blueColor").value;
//window.alert( color );
var r = document.querySelector(":root");
r.style.setProperty("--blue",color);
//얻어올때는 getProperty 설정할때는 setProperty
}
</script>
rs.getPropertyValue('--blue'); -> --blue라는 전역변수의 속성 알아오기(가져오기)
r.style.setPropertyValue('--blue'); -> --blue라는 속성으로 설정하기
위의 Get CSS Variable ~ 버튼을 누르면 (텍스트와 상관없이) [현재 배경색인 #1E90FF]가 alert으로 뜬다.
우측 Set CSS Variable ~ 버튼을 누르면 옆의 텍스트 색상으로 배경 색이 변한다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
/* 전역변수 :root선택자 사용 -> var() 함수를 사용해 사용가능 */
/* 변수 #1E90FF; */
:root{
/* --변수명:값; */
--blue:#1E90FF;
--white: #fff;
}
body{
background: var(--blue);
}
h2{
border-bottom: 2px solid var(--blue);
}
.container{
color: var(--blue);
background: var(--white);
padding: 15px;
}
.container button{
background: var(--white);
color:var(--blue);
border: 1px solid var(--blue);
padding: 5px;
}
</style>
</head>
<body>
<!-- css변수 -->
<h1>Lorem ipsum dolor sit amet.</h1>
<!-- .container>h2>lorem2^p*2>lorem15^button*2 -->
<div class="container">
<h2>Lorem ipsum.</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta ullam quae tempore aliquam commodi aperiam!</p>
<p>Cumque ipsum eius voluptatibus provident reiciendis fugiat veniam ratione fuga harum est maiores exercitationem architecto.</p>
<button>Yes</button>
<button>No</button>
</div>
<button onclick="getVariable()">Get CSS Variable with javascript</button>
<br>
<input type="text" id="blueColor" value="lightblue" />
<button onclick="setVariable()">Set CSS Variable with javascript</button>
<script>
function getVariable() {
/* :root 선택자 */
//document.getElementById(id) 이렇게 가져올게 아니라
var r = document.querySelector(":root");
var rs = getComputedStyle(r); //암기
//getComputedStyle(r); - root로부터 스타일(속성명, 값들)을 얻어오는 함수
window.alert( rs.getPropertyValue('--blue') );
}
function setVariable() {
var color = document.getElementById("blueColor").value;
//window.alert( color );
var r = document.querySelector(":root");
r.style.setProperty("--blue",color);
//얻어올때는 getProperty 설정할때는 setProperty
}
</script>
</body>
</html>
반응형