Вход

Просмотр полной версии : Получить переменную CSS из таблицы стилей.


voraa
12.01.2021, 22:33
Возникла такая проблема.
Есть таблица стилей. Нет (пока, не созданы еще) элементов, к которым эти стили применяются. В стилях есть переменные css.
Можно ли как-нибудь получить значения переменных (исключая разбор текста правил вручную).

Пример того, что имеется в виду

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" lang="ru">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >

<style id=stv>
#el{
width: 100px;
height: 50vh;
}
.cl {
width: 300px;
height: 100em;
color: rgb(255,220,220);
--var1: 100px;
}
</style>

</head>
<body>
<script>
let getStyle = (st, sel, name) => {
const rules = st.sheet.cssRules
for (let i=0; i<rules.length; i++) {
if (sel == rules[i].selectorText) {
return rules[i].style[name]
}
}
}

let st = document.getElementById('stv')

console.log('#el', 'width:', getStyle(st, '#el', 'width')) // 100px
console.log('.cl', 'color:', getStyle(st, '.cl', 'color')) // rgb(255,220,220)
console.log('.cl', '--var1:', getStyle(st, '.cl', '--var1')) // undefined ???
</script>
</body>
</html>


Значение свойств типа 'width', 'color' получить просто
Вот как бы получить значение --var1?

рони
12.01.2021, 23:13
исключая разбор текста правил вручную
:)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" lang="ru">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<style id=stv>
#el{
width: 100px;
height: 50vh;
}
.cl {
width: 300px;
height: 100em;
color: rgb(255,220,220);
--var1: 100px;
}
</style>
</head>
<body>
<script>
let getStyle = (st, sel, name) => {
const rules = st.sheet.cssRules
for (let i=0; i<rules.length; i++) {
if (sel == rules[i].selectorText) {
const reg = new RegExp(`(?<=${name}:\\s+)([^;]+)`);
return rules[i].cssText.match(reg)[0]
}
}
}
let st = document.getElementById('stv')
console.log('#el', 'width:', getStyle(st, '#el', 'width')) // 100px
console.log('.cl', 'color:', getStyle(st, '.cl', 'color')) // rgb(255,220,220)
console.log('.cl', '--var1:', getStyle(st, '.cl', '--var1')) // undefined ???
</script>
</body>
</html>

voraa
13.01.2021, 07:25
Проблема решена.
Про то, как делать правильно я даже не вспомнил. Наверно из-за хронической лени
Так все работает

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" lang="ru">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >

<style id=stv>
#el{
width: 100px;
height: 50vh;
}
.cl {
width: 300px;
height: 100em;
color: rgb(255,220,220);
--var1: 100px;
}
</style>

</head>
<body>
<script>
let getStyle = (st, sel, name) => {
const rules = st.sheet.cssRules
for (let i=0; i<rules.length; i++) {
if (sel == rules[i].selectorText) {
return rules[i].style.getPropertyValue(name)
}
}
}

let st = document.getElementById('stv')

console.log('#el', 'width:', getStyle(st, '#el', 'width')) // 100px
console.log('.cl', 'color:', getStyle(st, '.cl', 'color')) // rgb(255,220,220)
console.log('.cl', '--var1:', getStyle(st, '.cl', '--var1')) // 100px !!!
</script>
</body>
</html>



style[name] - дает только обычные свойства
getPropertyValue(name) дает все, и обычные и переменные.
Но лишних 15 знаков написать - это тяжко бывает.