简体   繁体   中英

How can i get value from css variable and change it automatically in several times (loop) using javascript

I wanted to change colors of my <h1> , <h2> and <h3> tags.

I've declared several variables in css like this:

:root{
    --color1 : #E11F28;
    --color2 : #F8981D;
    --color3 : #1DAD4B;
}

My question is how can I get that value and change it automatically with javascript in several times and loop (from number 1 into 3)

Here's a simple example

of course, you'll need to figure out how to get the right rule to change by changing

var declaration = document.getElementById('x').sheet.rules[0].style;

Seeing as you've written no javascript yourself, and shown absolutely nothing except a single style rule, that's one thing at least you'll need to figure out for yourself

but... it works

 function changecolors() { const changeit = style => { let p = style.getPropertyValue('color').replace(/\d/, x => x%3 + 1); style.setProperty('color', p); } var declaration = document.getElementById('x').sheet.rules; changeit(declaration[0].style) changeit(declaration[1].style) changeit(declaration[2].style) } setInterval(changecolors, 1000);
 :root { --color1: #E11F28; --color2: #F8981D; --color3: #1DAD4B; }
 <style id="x"> h1 { color: var(--color1); } h2 { color: var(--color1); } h3 { color: var(--color1); } </style> <h1>H1</h1> <h2>H2</h2> <h3>H3</h3>

what i really wanted is like this

 let html = document.querySelector(`html`); var color = ['red', 'green', 'blue']; var i =0; let uid = setInterval(() => { i = (i+1)%color.length; change = color[i]; html.style.setProperty(`--theme`, `${change}`); }, 1000);
 :root { --theme: black; } h1 { color: var(--theme); }
 <h1> Text Goes Here </h1>

big thx to my friend Muhammad vickry Yanto for creating this script

and thx for answering my question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM