И преимущество перед SASS-переменными
Перевод статьи Accessing and modifying CSS variables with Javascript с сайта hackernoon.com для CSS-live.ru, автор — ReasonCode
SASS-переменные с нами уже давно. Они позволяют задать переменную один раз во время выполнения (runtime) и использовать ее в нескольких местах. Уровень крутости — 3. Хотите уровень 6? Читайте дальше.
Взаимодействие с CSS-переменными при помощи JS после выполнения (post-runtime)
Создадим простую форму, которая будет использовать JS для динамического обновления CSS-переменных (в нашем случае, для изменения свойств color
и margin
у точки).
Демо на JSFiddle
Давайте рассмотрим детально.
:root { --footer-color: #2cba92; /* @reasonCode зеленый */ --palatte-padding-left: 0px } footer { width: 50px; height: 50px; margin-top: 20px; margin-left: var(--palatte-padding-left); /* 11 */ background-color: var(--footer-color); /* 12 */ border-radius: 15px; }
О CSS-псевдоклассе :root
можно прочесть на MDN и W3Schools (англ. яз.) Цитата с MDN:
CSS-псевдокласс
:root
находит корневой элемент дерева документа. Применимо к HTML,:root
находит элемент <html> и идентичен селектору по тегу html, но его специфичность выше.
Мы определили CSS-переменные в селекторе :root
. В строках 11-12 видно их использование. По стандарту CSS, переменная задается и используется с помощью префикса "--"
.
HTML
<body style="padding: 20px">
<label>Выберите свой любимый цвет:</label>
<input type="color" value="#2cba92">
<br/>
<label>Настройте отступ:</label>
<input type="range" id="margin" min="10" max="200" value="0">
<footer></footer>
</body>
Обратим внимание на атрибуты ползунка — элемента формы input
с type=”range”
. Они содержат минимальное (min
) и максимальное (max
) значения, а также исходное значение для value
. Также посмотрим на поле выбора цвета — элемент формы input
с type=”color”
. Для него исходный цвет задан атрибутом value="#2cba92"
.
Javascript
const footer = document.querySelector('footer') // 1 const inputs = [].slice.call(document.querySelectorAll('input')); // 2 inputs.forEach(input => input.addEventListener('change', handleUpdate)); // 4 inputs.forEach(input => input.addEventListener('mousemove', handleUpdate)); // 5 function handleUpdate(e) { // 7 if (this.type === 'color') { footer.style.setProperty('--footer-color', this.value) } else { footer.style.setProperty('--palatte-padding-left', this.value + 'px') } }
Разберем построчно:
1 — получили элемент footer
,
2 — получили коллекцию NodeList со всеми элементами input
на странице,
4 — добавили метод EventListener для события CHANGE,
5 — добавили метод EventListener для события MOUSEMOVE (обновляет динамический отступ у ползунка),
7 — функция для установки значения нужной CSS-переменной (обратим внимание, что мы добавили “px
” к переменной с отступом margin в строке 11).
Вот и всё про доступ к CSS-переменным и их изменение с помощью Javascript. Делитесь своим мнением, задавайте вопросы и, пожалуйста, читайте нас в Твиттере.
P.S. Это тоже может быть интересно:
Изучите CSS-переменные за 5 минут
Перевод статьи Per Harald Borgen: Learn CSS Variables in 5 minutes.
Пользовательские свойства CSS (CSS Custom Properties), также известные как переменные — большая победа для разработчиков интерфейсов. Они приносят силу переменных в CSS, что приводит к уменьшению дублирования, повышению читабельности и большей гибкости.
Кроме того, в отличие от переменных в препроцессорах CSS, нативные переменные CSS фактически являются частью DOM, что даёт много преимуществ. Поэтому они по существу похожи на переменные SASS и LESS на стероидах. В этой статье я проведу ускоренный курс о том, как работает эта новая технология.
Я также создал бесплатный интерактивный курс из 8 частей по CSS-переменным, поэтому ознакомьтесь с ним, если вы хотите стать экспертом по этой теме.
Зачем изучать переменные CSS?
Есть много причин использовать переменные в CSS. Одна из наиболее убедительных из них — уменьшение дублирования в вашей таблице стилей.
В приведённом выше примере гораздо лучше создать переменную для цвета #ffeead
, чем дублировать значение, что мы и делаем:
Это не только упрощает чтение кода, но и даёт больше гибкости, если нужно изменить цвет.
Сейчас в течение многих лет подобное на самом деле уже возможно делать, используя SASS- и LESS-переменные. Тем не менее, есть несколько преимуществ в случае CSS-переменных:
- Они не требуют никаких инструментов для работы, поскольку они поддерживаются самим браузером. Таким образом, вам не нужна дополнительная настройка, как начать с ними работу, в отличие от SASS и LESS.
- Они находятся в DOM, что открывает массу возможностей, о которых я расскажу в этой статье и в своём предстоящем курсе.
Теперь давайте начнём изучение CSS-переменных!
Объявление первой переменной CSS
Чтобы объявить переменную, вам сначала нужно решить, в какой области должна быть переменная. Если вы хотите, чтобы она была доступна глобально, просто определите её в псевдоклассе :root
, который соответствует корневому элементу в дереве документов (обычно это тег <html>
).
Поскольку переменные наследуются, следующий ниже код следует вашу переменную доступной во всём вашем приложении, так как все ваши DOM-элементы являются потомками тега <html>
.
:root { --main-color: #ff6f69; }
Как вы можете видеть, вы объявляете переменную точно так же, как вы бы установили любое свойство CSS. Однако переменная должна начинаться с двух дефисов (--
).
Для получения доступа к переменной, вам нужно использовать функцию var()
и передать имя переменной в качестве первого параметра.
#title { color: var(--main-color); }
И это назначит вашему заголовку цвет #ff6f69
:
Функция var
поддерживает второй параметр, фолбэк, то есть значение (или также CSS-переменная), которое будет использоваться, если переменная, переданная первым параметром, не определена, например:
#title { color: var(--main-color, black); }
Если переменная main-color
недоступна, то будет использоваться черный цвет (black
).
Объявление локальной переменной
Вы также можете создавать переменные с локальной областью видимости, который будут доступны только для того элемента, в котором они были объявлены, включая его дочерние элементы. Это имеет смысл делать, если вы знаете, что переменная будет использоваться только в определённой части (или частях) вашего приложения.
Например, у вас может быть окно с предупреждением, в котором используется определённый цвет, который не используется в других частях приложения. В этом случае скорее всего нецелесообразно определять этот цвет в глобальной области:
.alert { --alert-color: #ff6f69; }
Теперь эта переменная может использоваться в дочерних элементах:
.alert p { color: var(--alert-color); border: 1px solid var(--alert-color); }
Если вы попытаетесь использовать переменную alert-color
в другой части приложения, например, в навигационной панели, это не сработает: браузер просто проигнорирует такую строку CSS (за исключением, если не был предоставлен фолбэк вторым параметром).
Лёгкость реализации адаптивности с переменными
Большое преимущество CSS-переменных заключается в том, что они имеют доступ к DOM. Чего нельзя сказать о LESS или SASS, поскольку их переменные вставляются в обычный CSS.
На практике это означает, что вы можете, например, изменить переменные в зависимости от ширины экрана:
:root { --main-font-size: 16px; } media all and (max-width: 600px) { :root { --main-font-size: 12px; } }
Всего четыре строки кода и вы изменили базовый размер шрифта при просмотре вашего приложения на маленьком экране. Довольно элегантно, не так ли?
Как получить доступ к переменным из JavaScript?
Доступ к CSS-переменным с помощью JavaScript — это ещё одно из преимуществ того, что CSS-переменные являются частью DOM. Вы можете обновлять их значения, что может пригодится, если вы хотите дать возможность вашим пользователям изменять внешний вид сайта (например, изменить размер шрифта).
Давайте продолжим на примере в начале этой статьи. Получение значение CSS-переменной через JavaScript занимает три строки кода:
var root = document.querySelector(':root'); var rootStyles = getComputedStyle(root); var mainColor = rootStyles.getPropertyValue('--main-color'); console.log(mainColor); // '#ffeead'
Для обновления переменной CSS, просто вызовите метод setProperty
на элементе, в котором была объявлена переменная, и передайте имя переменной в качестве первого параметра и новое значение — вторым.
root.style.setProperty('--main-color', '#88d8b0');
Изменение основного цвета повлияет на весь внешний вид приложения, что идеально подходит для случаев, когда пользователи могут выбрать тему на вашем сайте.
Поддержка браузеров
В данный момент 77 процентов от глобального трафика сайтов поддерживают переменные CSS, причём почти 90 процентов в США. Мы уже используем CSS-переменные на Scrimba.com некоторое время, поскольку наша аудитория технически подкована и в основном использует современные браузеры.
Хорошо, на этом всё. Надеюсь, вы узнали что-то новое для себя.
Если вы хотите изучить его правильно, обязательно посмотрите мой бесплатный курс по CSS-переменным.
Слушайте наш подкаст в iTunes и SoundCloud, читайте нас на Medium, контрибьютьте на GitHub, общайтесь в группе Telegram, следите в Twitter и канале Telegram, рекомендуйте в VK и Facebook.
Alright, I’m creating a system for my webpage that allows users to change the theme. How I want to accomplish this is by having all the colors as variables, and the colors are set in the :root part of the CSS.
What I want to do is change those colors via JavaScript. I looked up how to do it, but nothing that I attempted actually worked properly. Here’s my current code:
CSS:
:root {
--main-color: #317EEB;
--hover-color: #2764BA;
--body-color: #E0E0E0;
--box-color: white;
}
JS:
(Code to set the theme, it’s ran on the click of a button) — I didn’t bother adding the :root change to the other 2 themes since it doesn’t work on the Dark theme
function setTheme(theme) {
if (theme == 'Dark') {
localStorage.setItem('panelTheme', theme);
$('#current-theme').text(theme);
$(':root').css('--main-color', '#000000');
}
if (theme == 'Blue') {
localStorage.setItem('panelTheme', 'Blue');
$('#current-theme').text('Blue');
alert("Blue");
}
if (theme == 'Green') {
localStorage.setItem('panelTheme', 'Green');
$('#current-theme').text('Green');
alert("Green");
}
}
(Code that is ran when the html is loaded)
function loadTheme() {
//Add this to body onload, gets the current theme. If panelTheme is empty, defaults to blue.
if (localStorage.getItem('panelTheme') == '') {
setTheme('Blue');
} else {
setTheme(localStorage.getItem('panelTheme'));
$('#current-theme').text(localStorage.getItem('panelTheme'));
}
}
It shows the alert, but does not actually change anything. Can someone point me in the right direction?
asked Jun 14, 2016 at 2:08
DaedalusDaedalus
3,2304 gold badges14 silver badges18 bronze badges
7
Thank you @pvg for providing the link. I had to stare at it for a little to understand what was going on, but I finally figured it out.
The magical line I was looking for was this:
document.documentElement.style.setProperty('--your-variable', '#YOURCOLOR');
That did exactly what I wanted it to do, thank you very much!
answered Jun 14, 2016 at 2:54
DaedalusDaedalus
3,2304 gold badges14 silver badges18 bronze badges
10
I think this is cleaner and easier to remember.
to set/get css variables to/from :root
const root = document.querySelector(':root');
// set css variable
root.style.setProperty('--my-color', 'blue');
// to get css variable from :root
const color = getComputedStyle(root).getPropertyValue('--my-color'); // blue
Example: setting multiple variables all at once
const setVariables = vars => Object.entries(vars).forEach(v => root.style.setProperty(v[0], v[1]));
const myVariables = {
'--color-primary-50': '#eff6ff',
'--color-primary-100': '#dbeafe',
'--color-primary-200': '#bfdbfe',
'--color-primary-300': '#93c5fd',
'--color-primary-400': '#60a5fa',
'--color-primary-500': '#3b82f6',
'--color-primary-600': '#2563eb',
'--color-primary-700': '#1d4ed8',
'--color-primary-800': '#1e40af',
'--color-primary-900': '#1e3a8a',
};
setVariables(myVariables);
answered May 12, 2022 at 2:14
To use the values of custom properties in JavaScript, it is just like standard properties.
// get variable from inline style
element.style.getPropertyValue("--my-variable");
// get variable from wherever
getComputedStyle(element).getPropertyValue("--my-variable");
// set variable on inline style
element.style.setProperty("--my-variable", 4);
answered May 15, 2020 at 20:33
iProDeviProDev
5276 silver badges5 bronze badges
1
I came here looking how to toggle the :root
color-scheme with JavaScript, which sets the browser to dark mode (including the scroll bars) like this:
:root {
color-scheme: dark;
}
using the @Daedalus answer above, this is how I implemented my dark mode detection from user preference:
const userPrefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
const preferredTheme = userPrefersDarkMode ? 'dark' : 'light';
document.documentElement.style.setProperty("color-scheme", preferredTheme);
or with saved toggle:
const savedTheme = localStorage.getItem('theme');
if (savedTheme == 'dark') {
thisTheme = 'light'
}
else {
thisTheme = 'dark'; // the default when never saved is dark
}
document.documentElement.style.setProperty("color-scheme", thisTheme);
localStorage.setItem('theme', thisTheme);
see also the optional meta tag in the header:
<meta name="color-scheme" content="dark light">
answered May 9, 2021 at 19:08
gojimmypigojimmypi
3713 silver badges6 bronze badges
old jquery magic still working too
$('#yourStyleTagId').html(':root {' +
'--your-var: #COLOR;' +
'}');
answered Jun 4, 2018 at 21:28
v2pv2p
6392 gold badges10 silver badges19 bronze badges
TL;DR
A solution to the problem could be the below code:
const headTag = document.getElementsByTagName('head')[0];
const styleTag = document.createElement("style");
styleTag.innerHTML = `
:root {
--main-color: #317EEB;
--hover-color: #2764BA;
--body-color: #E0E0E0;
--box-color: white;
}
`;
headTag.appendChild(styleTag);
Explanation:
Although @Daedalus answer with document.documentElement
does the job pretty well, a slightly better approach is to add the styling into a <style>
HTML tag (solution proposed).
If you add document.documentElement.style
then all the CSS variables are added into the html
tag and they are not hidden:
On the other hand, with the proposed code:
const headTag = document.getElementsByTagName('head')[0];
const styleTag = document.createElement("style");
styleTag.innerHTML = `
:root {
--main-color: #317EEB;
--hover-color: #2764BA;
--body-color: #E0E0E0;
--box-color: white;
}
`;
headTag.appendChild(styleTag);
the HTML tag will be cleaner and if you inspect the HTML tag you can also see the :root
styling as well.
answered Apr 18, 2022 at 6:20
1
Read only, retrieve all CSS --root
rules in an array, without using .getComputedStyle()
.
This may allow to retrieve values before full DOM content load, to create modules that use global root theme variables, but not via CSS. (canvas context…)
/* Retrieve all --root CSS variables
* rules into an array
* Without using getComputedStyle (read string only)
* On this example only the first style-sheet
* of the document is parsed
*/
console.log(
[...document.styleSheets[0].rules]
.map(a => a.cssText.split(" ")[0] === ":root" ?
a.cssText.split("{")[1].split("}")[0].split("--") : null)
.filter(a => a !== null)[0]
.map(a => "--"+a)
.slice(1)
)
:root {
--gold: hsl(48,100%,50%);
--gold-lighter: hsl(48,22%,30%);
--gold-darker: hsl(45,100%,47%);
--silver: hsl(210,6%,72%);
--silver-lighter: hsl(0,0%,26%);
--silver-darker: hsl(210,3%,61%);
--bronze: hsl(28,38%,67%);
--bronze-lighter: hsl(28,13%,27%);
--bronze-darker: hsl(28,31%,52%);
}
answered Apr 3, 2022 at 23:11
NVRMNVRM
10.6k1 gold badge82 silver badges85 bronze badges
/*My style*/
:root {
--hl-color-green: green;
}
/*My update*/
* {
--hl-color-green: #0cc120;
}
answered Sep 16, 2022 at 14:07
Alright, I’m creating a system for my webpage that allows users to change the theme. How I want to accomplish this is by having all the colors as variables, and the colors are set in the :root part of the CSS.
What I want to do is change those colors via JavaScript. I looked up how to do it, but nothing that I attempted actually worked properly. Here’s my current code:
CSS:
:root {
--main-color: #317EEB;
--hover-color: #2764BA;
--body-color: #E0E0E0;
--box-color: white;
}
JS:
(Code to set the theme, it’s ran on the click of a button) — I didn’t bother adding the :root change to the other 2 themes since it doesn’t work on the Dark theme
function setTheme(theme) {
if (theme == 'Dark') {
localStorage.setItem('panelTheme', theme);
$('#current-theme').text(theme);
$(':root').css('--main-color', '#000000');
}
if (theme == 'Blue') {
localStorage.setItem('panelTheme', 'Blue');
$('#current-theme').text('Blue');
alert("Blue");
}
if (theme == 'Green') {
localStorage.setItem('panelTheme', 'Green');
$('#current-theme').text('Green');
alert("Green");
}
}
(Code that is ran when the html is loaded)
function loadTheme() {
//Add this to body onload, gets the current theme. If panelTheme is empty, defaults to blue.
if (localStorage.getItem('panelTheme') == '') {
setTheme('Blue');
} else {
setTheme(localStorage.getItem('panelTheme'));
$('#current-theme').text(localStorage.getItem('panelTheme'));
}
}
It shows the alert, but does not actually change anything. Can someone point me in the right direction?
asked Jun 14, 2016 at 2:08
DaedalusDaedalus
3,2304 gold badges14 silver badges18 bronze badges
7
Thank you @pvg for providing the link. I had to stare at it for a little to understand what was going on, but I finally figured it out.
The magical line I was looking for was this:
document.documentElement.style.setProperty('--your-variable', '#YOURCOLOR');
That did exactly what I wanted it to do, thank you very much!
answered Jun 14, 2016 at 2:54
DaedalusDaedalus
3,2304 gold badges14 silver badges18 bronze badges
10
I think this is cleaner and easier to remember.
to set/get css variables to/from :root
const root = document.querySelector(':root');
// set css variable
root.style.setProperty('--my-color', 'blue');
// to get css variable from :root
const color = getComputedStyle(root).getPropertyValue('--my-color'); // blue
Example: setting multiple variables all at once
const setVariables = vars => Object.entries(vars).forEach(v => root.style.setProperty(v[0], v[1]));
const myVariables = {
'--color-primary-50': '#eff6ff',
'--color-primary-100': '#dbeafe',
'--color-primary-200': '#bfdbfe',
'--color-primary-300': '#93c5fd',
'--color-primary-400': '#60a5fa',
'--color-primary-500': '#3b82f6',
'--color-primary-600': '#2563eb',
'--color-primary-700': '#1d4ed8',
'--color-primary-800': '#1e40af',
'--color-primary-900': '#1e3a8a',
};
setVariables(myVariables);
answered May 12, 2022 at 2:14
To use the values of custom properties in JavaScript, it is just like standard properties.
// get variable from inline style
element.style.getPropertyValue("--my-variable");
// get variable from wherever
getComputedStyle(element).getPropertyValue("--my-variable");
// set variable on inline style
element.style.setProperty("--my-variable", 4);
answered May 15, 2020 at 20:33
iProDeviProDev
5276 silver badges5 bronze badges
1
I came here looking how to toggle the :root
color-scheme with JavaScript, which sets the browser to dark mode (including the scroll bars) like this:
:root {
color-scheme: dark;
}
using the @Daedalus answer above, this is how I implemented my dark mode detection from user preference:
const userPrefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
const preferredTheme = userPrefersDarkMode ? 'dark' : 'light';
document.documentElement.style.setProperty("color-scheme", preferredTheme);
or with saved toggle:
const savedTheme = localStorage.getItem('theme');
if (savedTheme == 'dark') {
thisTheme = 'light'
}
else {
thisTheme = 'dark'; // the default when never saved is dark
}
document.documentElement.style.setProperty("color-scheme", thisTheme);
localStorage.setItem('theme', thisTheme);
see also the optional meta tag in the header:
<meta name="color-scheme" content="dark light">
answered May 9, 2021 at 19:08
gojimmypigojimmypi
3713 silver badges6 bronze badges
old jquery magic still working too
$('#yourStyleTagId').html(':root {' +
'--your-var: #COLOR;' +
'}');
answered Jun 4, 2018 at 21:28
v2pv2p
6392 gold badges10 silver badges19 bronze badges
TL;DR
A solution to the problem could be the below code:
const headTag = document.getElementsByTagName('head')[0];
const styleTag = document.createElement("style");
styleTag.innerHTML = `
:root {
--main-color: #317EEB;
--hover-color: #2764BA;
--body-color: #E0E0E0;
--box-color: white;
}
`;
headTag.appendChild(styleTag);
Explanation:
Although @Daedalus answer with document.documentElement
does the job pretty well, a slightly better approach is to add the styling into a <style>
HTML tag (solution proposed).
If you add document.documentElement.style
then all the CSS variables are added into the html
tag and they are not hidden:
On the other hand, with the proposed code:
const headTag = document.getElementsByTagName('head')[0];
const styleTag = document.createElement("style");
styleTag.innerHTML = `
:root {
--main-color: #317EEB;
--hover-color: #2764BA;
--body-color: #E0E0E0;
--box-color: white;
}
`;
headTag.appendChild(styleTag);
the HTML tag will be cleaner and if you inspect the HTML tag you can also see the :root
styling as well.
answered Apr 18, 2022 at 6:20
1
Read only, retrieve all CSS --root
rules in an array, without using .getComputedStyle()
.
This may allow to retrieve values before full DOM content load, to create modules that use global root theme variables, but not via CSS. (canvas context…)
/* Retrieve all --root CSS variables
* rules into an array
* Without using getComputedStyle (read string only)
* On this example only the first style-sheet
* of the document is parsed
*/
console.log(
[...document.styleSheets[0].rules]
.map(a => a.cssText.split(" ")[0] === ":root" ?
a.cssText.split("{")[1].split("}")[0].split("--") : null)
.filter(a => a !== null)[0]
.map(a => "--"+a)
.slice(1)
)
:root {
--gold: hsl(48,100%,50%);
--gold-lighter: hsl(48,22%,30%);
--gold-darker: hsl(45,100%,47%);
--silver: hsl(210,6%,72%);
--silver-lighter: hsl(0,0%,26%);
--silver-darker: hsl(210,3%,61%);
--bronze: hsl(28,38%,67%);
--bronze-lighter: hsl(28,13%,27%);
--bronze-darker: hsl(28,31%,52%);
}
answered Apr 3, 2022 at 23:11
NVRMNVRM
10.6k1 gold badge82 silver badges85 bronze badges
/*My style*/
:root {
--hl-color-green: green;
}
/*My update*/
* {
--hl-color-green: #0cc120;
}
answered Sep 16, 2022 at 14:07
Одно из самых серьёзных противостояний в мире веб-разработки — CSS против JavaScript. У обоих есть свои достоинства, собственный синтаксис и идеи, иногда понять их может быть непросто. Но есть способы заставить их общаться и использовать достоинства каждого.
С позиции JavaScript для установки различных CSS-свойств HTML-элементу, требуется найти его в DOM и получить доступ к нему. После добавления стилей, у этого элемента появляется атрибут style
, который вы не стали бы, наверное, писать вручную.
Ещё один способ доступа к CSS-свойствам из JavaScript — использовать настраиваемые CSS-свойства, они также известны, как «CSS-переменные» (CSS variables), которые можно определять с помощью синтаксиса --
. Так:
:root {
--pagebackground: powderblue;
}
body {
background: var(--pagebackground);
}
Это «переменные», поэтому их можно неоднократно использовать в таблице стилей.
Получить к ним доступ и управлять значениями этих переменных можно с помощью JavaScript. В этом примере настраиваемое CSS-свойство устанавливается для корневого элемента документа. Его можно прочитать так:
let bg = getComputedStyle(document.documentElement).
getPropertyValue('--pagebackground');
И его можно установить с помощью JavaScript, получив доступ к стилю корневого элемента (или вообще любого другого элемента с настраиваемыми свойствами), так:
document.documentElement.style.setProperty('--pagebackground', 'firebrick');
See this code Testing CSS Custom properties interaction on x.xhtml.ru.
Но самое выдающееся во всей этой истории то, что используя возможности JavaScript, можно предоставить CSS то, к чему он не может получить доступ. Например, CSS не может прочитать координаты курсора мыши, а JavaScript может.
Для начала, в CSS надо определить пару свойств --mouse-x
и --mouse-y
, а также установить им начальные значения — 0
:
:root {
--mouse-x: 0;
--mouse-y: 0;
}
Затем, в JavaScript следует добавить документу обработчик mousemove
. Тогда при движении курсора можно получать его координаты и управлять этими двумя CSS-свойствами с помощью JavaScript:
let root = document.documentElement
document.addEventListener('mousemove', e => {
root.style.setProperty('--mouse-x', e.x);
root.style.setProperty('--mouse-y', e.y);
});
В-общем, дело нехитрое. Поскольку настраиваемые CSS-свойства реагируют на движение мыши и изменяют свое значение, теперь можно, например, показать кружок и заставить его двигаться вслед за курсором, так:
HTML:
<div id="ball"></div>
CSS
:root {
--mouse-x: 0;
--mouse-y: 0;
}
#ball {
width: 20px;
height: 20px;
background: white;
border-radius: 100%;
transform: translate(
calc(calc(var(--mouse-x) - 10) * 1px),
calc(calc(var(--mouse-y) - 10) * 1px)
);
}
Здесь некоторые пояснения к CSS:
- ширина и высота
DIV
установлены равными 20 пикселей, а фон — белый - добавление
border-radius: 100%
гарантирует, что из квадрата получится круг. - затем используется
transform: translate
, чтобы позиционировать круг на экране. Это может быть что-то вродеtransform: translate (200px, 300px)
, чтобы расположить наш шар на 200 пикселей по горизонтали и 300 пикселей по вертикали относительно левого верхнего угла. - поскольку JavaScript возвращает для настраиваемого CSS-свойства числовое значение, его необходимо преобразовать в пиксели, умножив на
1px
. - так как размер шара составляет 20 пикселей, то чтобы поместить его центр в точки
--mouse-x
и--mouse-y
, нужно вычесть из координат 10.
Этот трюк позволяет выполнять сложные вычисления, считывать состояние браузера и внешнее взаимодействие с ним в JavaScript, затем передавать результат в CSS и изменять его.
See this code Mouse position as custom CSS property on x.xhtml.ru.
Sharing data between CSS and JavaScript using custom properties.
Домой ← Публикации ← Изменение CSS свойств с помощью JavaScript
15 апреля 2015
Приветствую, друзья!
Данная статья пригодится новичкам в веб-программировании. Буду подразумевать, что вам знаком «СИшный» синтаксис, который лежит в основе JavaScript, и получение ссылки на элемент — метод getElementById и сопутствующие — проблем не вызывает. Естественно, основы HTML и CSS вам также должны быть известны.
Для доступа к стилям существует специальное свойство объекта — style. Пусть на странице определён элемент с идентификатором elem:
<div id="elem">DIV</div>
Тогда, для доступа к его «стилевым» свойствам, можно использовать такой код (не пытайтесь использовать, вырвано из контекста!):
document.getElementById('elem').style.ЦС
где ЦС — то свойство, к которому нужно обратиться или изменить.
Далее начинается пусть небольшая, но магия. Вам известны различные CSS свойства: background, border, display, font-size и т. п. Обратите внимание на последнее, в котором есть символ — (минус на клавиатуре). В названиях переменных такие дефисы использовать нельзя, поскольку в контексте программы они интерпретируются как знак вычитания. Для логического обоснования, маленький пример:
font-size
Если бы интерпретатор JavaScript допускал в именах символ минус, ему пришлось бы выполнить дополнительные действия:
- Проверить существование переменной font-size.
- Если её нет, попытаться выполнить арифметическое действие «вычитание» значения size из font.
Поэтому, имена свойств требуется «причесать» (нормализовать) для использования в коде. К счастью, определено всего 2 простых правила:
- Если знака минус нет (margin, border, width и прочее) — записывается как есть:
// установить элементу ширину в 30 пикселей document.getElementById('elem').style.width = '30px';
- Если знак минус присутствует, то он убирается, а следующая буква переводится в верхний регистр: background-color → backgroundСolor, z-index → zIndex и т. д.:
// Сделать фон красным document.getElementById('elem').style.backgroundColor = '#FF0000';
Вот так! Всё очень просто. Если вы знаете CSS свойства, значит, имеете возможность свободно ими рулить и в JavaScript. А попрактиковаться можете уже сейчас.
Ниже дан небольшой пример изменения свойств элемента с помощью JS. Если видете в названии слово color, это подразумевает задание цвета.
Думаю, нет нужды объяснять, что присвоение неверных значений игронируется?
- Попробуйте управлять этим списком.
- Сделать это совсем просто.
- Можете выбрать свойство color.
- Установите для него значение #0000dd
Выберите CSS-свойство и укажите корректное значение для него:
Автор публикации
2 070
x64 (aka andi)
Комментарии: 2893Публикации: 405Регистрация: 02-04-2009
Загрузка…