자바스크립트를 통해 CSS 사용자 지정 속성(일명 CSS 변수) 접근
CSS 사용자 지정 속성(로 액세스하는 속성)을 어떻게 얻고 설정합니까?var(…)
스타일시트에서) 자바스크립트(평판 또는 jQuery)를 사용할 수 있습니까?
성공하지 못한 시도는 다음과 같습니다. 버튼을 클릭하면 일상적인 방식이 바뀝니다.font-weight
속성이지만 관습은 아닙니다.--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>
사용가능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
네이티브 솔루션
CSS3 변수를 얻거나 설정하는 표준 방법은 다음과 같습니다..setProperty()
그리고..getPropertyValue()
.
변수가 전역인 경우(에 선언됨):root
값을 가져오고 설정하는 데 다음을 사용할 수 있습니다.
// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');
그러나 게터는 를 사용하여 설정된 경우에만 var의 값을 반환합니다. CSS 선언을 통해 설정된 경우 를 반환합니다.undefined
. 다음 예제에서 확인합니다.
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
예상치 못한 행동을 피하기 위해서는getComputedStyle()
메서드, 호출하기 전에.getPropertyValue()
. 그러면 게터는 다음과 같이 보일 것입니다.
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
제 생각에 CSS 변수에 접근하는 것은 더 간단하고 빠르고 직관적이고 자연스러운 것이어야 합니다...
나의 개인적인 접근법
구현했습니다.CSSGlobalVariables
문서에 있는 모든 활성 CSS 전역 변수를 자동으로 감지하고 개체에 패킹하여 보다 쉽게 접근하고 조작할 수 있는 작은(<3kb) 자바스크립트 도우미.
// get the document CSS global vars
let cssVar = new CSSGlobalVariables();
// set a new value to --myVariable
cssVar.myVariable = 'red';
// get the value of --myVariable
console.log( cssVar.myVariable );
Object 속성에 적용된 변경 내용은 CSS 변수로 자동 변환됩니다.
다음 사이트에서 사용 가능: https://github.com/colxi/css-global-variables
다음 예제는 CSS 변수라고도 알려진 사용자 지정 CSS 속성을 활용하여 자바스크립트 또는 jQuery를 사용하여 배경을 변경하는 방법을 보여줍니다(여기서 더 읽어보십시오).보너스: 코드는 CSS 변수를 사용하여 글꼴 색을 변경할 수 있는 방법도 나타냅니다.
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>
jQuery를 사용하면 사용자 지정 속성을 다른 값으로 설정하기 위해 이 응답이 실제로 답변을 유지합니다.Body Element의 get() 메서드를 사용하여 기본 DOM 구조에 액세스할 수 있고 Body Element를 반환하므로 Custom Property의 코드 설정이 용이합니다.--mycolor
새로운 가치로
getComputedStyle 함수를 사용하여 cs 변수를 가져올 수 있습니다.여기 예가 있습니다.
const colors = document.querySelectorAll(".color");
const result = document.getElementById("result");
colors.forEach((color) => color.addEventListener("click", changeColor));
function changeColor(event) {
const target = event.target;
// get color
const color = getComputedStyle(target).getPropertyValue("--clr");
document.body.style.backgroundColor = color;
// active color
colors.forEach((color) => color.classList.remove("active"));
target.classList.add("active");
result.textContent = getComputedStyle(target).getPropertyValue("--clr")
}
result.textContent = "#1dd1a1";
body{
background-color: #1dd1a1;
}
.colors{
position: absolute;
padding: 2rem;
display: flex;
gap: 1rem;
}
.color{
display: inline-block;
width: 2rem;
height: 2rem;
background-color: var(--clr);
border-radius: 50%;
cursor: pointer;
transition: $time-unit;
}
.color.active{
border: .2rem solid #333;
transform: scale(1.25);
}
<h1>Click to change Background</h1>
<section class="colors">
<span class="color active" style="--clr: #1dd1a1"></span>
<span class="color" style="--clr: #ff6b6b"></span>
<span class="color" style="--clr: #2e86de"></span>
<span class="color" style="--clr: #f368e0"></span>
<span class="color" style="--clr: #ff9f43"></span>
</section>
Current Color: <span id="result"></span>
언급URL : https://stackoverflow.com/questions/36088655/accessing-a-css-custom-property-aka-css-variable-through-javascript
'programing' 카테고리의 다른 글
PowerShell로 특정 이름의 폴더를 재귀적으로 삭제하려면 어떻게 해야 합니까? (0) | 2023.10.29 |
---|---|
민첩한 업로더 워드프레스 구현 (0) | 2023.10.29 |
UI 글꼴 - 시스템 얇은 글꼴을 가져오는 방법 (0) | 2023.10.29 |
뒤로 가기 단추에서 텍스트를 변경하는 방법 (0) | 2023.10.29 |
리소스를 로드하고 해당 리소스의 내용을 봄에 문자열로 사용하는 방법 (0) | 2023.10.29 |