- Как изменить цвет фона веб-страницы с помощью JavaScript
- Читайте также
- Похожие примеры:
- Javascript изменение цвета фона
- Результат замены цвета при наведении мышки на элемент:
- Изменить цвет(background) нажав по элементу.
- Результат замены цвета при клике на элемент:
- Изменение цвета (background) javascript скриптом
- Далее скрипт изменения цвета (background) javascript скриптом
- Скрипт javascript для замены background при нажатии
- Пример изменения background при нажатии javascript
- Изменение цвета кнопки (background) javascript
- Алгоритм смены цвета кнопки.
- Соберем весь код смены цвета с помощью javascript
- Style backgroundColor Property
- See Also:
- Syntax
- Property Values
- Technical Details
- Browser Support
- More Examples
- Example
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Javascript изменение цвета фона
- # Table of Contents
- # Change the page’s background color on click
- # Change the element’s background color on click
- # Change another element’s background color on click
- # Toggle an Element’s background color on click using JS
Как изменить цвет фона веб-страницы с помощью JavaScript
Свойство style используется для получения, а также для установки встроенного стиля элемента, например:
// Функция изменения цвета фона веб-страницы function changeBodyBg(color) < document.body.style.background = color; >// Функция изменения цвета фона заголовка function changeHeadingBg(color) This is a heading
This is a paragraph of text.
Читайте также
Похожие примеры:
Javascript изменение цвета фона
Для того, чтобы сделать сменяемость цвета с помощью javascript, при наведении мышки. Нам понадобится:
Нам понадобится элемент DOM div,
+ onmouseover — когда мышка будет попадать на элемент,
И когда мышка будет покидать элемент — onmouseleave и внутри функций, в зависимости от действия будем изменять цвет, или возвращать первоначальный:
example.onmouseleave = function() example.style.background= «yellow»;
>;
Результат замены цвета при наведении мышки на элемент:
Изменить цвет(background) нажав по элементу.
В этом пункте разберем замену background цвета по клику с расположением js кода внутри тега.
Для того, чтобы изменить цвет элемента нажав по нему, нам понадобится, как и в выше проведенном пункте:
Пусть это будет элемент DOM div,
Соберем это все в одн целое:
Результат замены цвета при клике на элемент:
Для того, чтобы увидеть изменение цвета элемента при нажатии на него нажмите по блоку!
Изменение цвета (background) javascript скриптом
Выше я уже рассмотрел один из вариантов изменения цвета (background) javascript внутри тега.
Теперь тоже самое(ну или похожее. ) сделаем внутри скрипта.
Стили для блока выделим в отдельный тег style
Далее скрипт изменения цвета (background) javascript скриптом
Используем один из способов onclick
Нам понадобится getElementById для получения объекта.
Ну и далее простое условие с проверкой, что внутри атрибута style , если цвет красный
Во всех други случаях, т.е. иначе(else) меняем на красный.
Скрипт javascript для замены background при нажатии
Не забываем. если не сделано onload, то скрипт должен находиться под выше приведенным кодом элемента, в котором собираемся изменить background при нажатии
if(if_id .style . background == «red»)
if_id .style . background = «#efefef»;
if_id .style . background = «red»;
Пример изменения background при нажатии javascript
Нам остается разместить приведенный код прямо здесь. Чтобы проверить как работает изменение background при нажатии javascript кликните по ниже идущему цветному блоку.
Изменение цвета кнопки (background) javascript
С помощью самописного скрипта, заставим кнопки менять цвет.
Алгоритм смены цвета кнопки.
У кнопки должно быть что-то одинаковое — «class» = click_me.
И что-то разное. уникальное, это id.
Получим имена класса и ид:
Условие -если нажали по нашей кнопке с классом:
Получаем объект из имени(которое получили раннее):
При покрашенной кнопке возвращаем нажатой кнопке её цвет по умолчанию:
Иначе, всем кнопкам с классом возвращаем в цикле её цвет по умолчанию и только той кнопке, по которой нажали изменяем цвет::
else
var links = document.querySelectorAll(«.click_me»);
links.forEach(link => link.setAttribute(«style», «background:#efefef»);
>)
if_id .style . background = «red»;
>
Соберем весь код смены цвета с помощью javascript
the_class = e . target.className;
if(if_id .style . background == «red»)
if_id .style . background = «#efefef»;
var links = document.querySelectorAll(«.click_me»);
if_id .style . background = «red»;
Style backgroundColor Property
The backgroundColor property sets or returns the background color of an element.
See Also:
Syntax
Return the backgroundColor property:
Set the backgroundColor property:
Property Values
Value | Description |
---|---|
color | Specifies the background color. Look at CSS Color Values for a complete list of possible color values |
transparent | Default. The background color is transparent (underlying content will shine through) |
initial | Sets this property to its default value. Read about initial |
inherit | Inherits this property from its parent element. Read about inherit |
Technical Details
Default Value: | transparent |
---|---|
Return Value: | A String, representing the background color |
CSS Version | CSS1 |
Browser Support
backgroundColor is a CSS1 (1996) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
More Examples
Example
Set a background color of a specific element:
Example
Return the background color of a specific element:
Example
Return the background color of a document:
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Javascript изменение цвета фона
Last updated: Jan 11, 2023
Reading time · 4 min
# Table of Contents
# Change the page’s background color on click
To change the page’s background color on click:
- Add a click event listener to an element.
- Each time the element is clicked, set the document.body.style.backgroundColor property to a specific color.
Here is the HTML for the example.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> div id="box">Some text herediv> button id="btn">Buttonbutton> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick(event) // 👇️ change background color document.body.style.backgroundColor = 'salmon'; // 👇️ optionally change text color // document.body.style.color = 'white'; >);
We added a click event listener to the button, so a function is invoked every time the button is clicked.
Each time the button is clicked, we set the document.body.style.backgroundColor property to salmon and change the page’s background color.
# Change the element’s background color on click
To change an element’s background color on click:
- Add a click event listener to the element.
- Assign the event object to a variable in the function.
- Set the event.target.style.backgroundColor property to the specific background color.
Copied!const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick(event) // 👇️ change background color event.target.style.backgroundColor = 'salmon'; // 👇️ optionally change text color // event.target.style.color = 'white'; >);
Every time the button from the example is clicked, its own background color gets set.
We used the target property on the event object. The target property is a reference to the object (element) on which the event was dispatched.
You can console.log the target property to see the DOM element which was clicked by the user.
Copied!const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick(event) console.log(event.target); // 👇️ change background color event.target.style.backgroundColor = 'salmon'; // 👇️ optionally change text color // event.target.style.color = 'white'; >);
If you click on the button and look at your console output, you’ll see the button element being logged.
# Change another element’s background color on click
To change another element’s background color on click:
- Add a click event listener to one of the elements.
- Each time the element is clicked, change the style.backgroundColor property of the other element.
Here is the HTML for the example.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> div id="box">Some text herediv> button id="btn">Buttonbutton> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick(event) const box = document.getElementById('box'); box.style.backgroundColor = 'coral'; // 👇️ optionally change text color // box.style.color = 'white'; >);
Each time the button is clicked, we change the div ‘s background color to coral .
# Toggle an Element’s background color on click using JS
To toggle an element’s background color on click:
- Add a click event listener to the element.
- Each time the element is clicked, check the element’s current background color and change it.
- Use the element.style.backgroundColor property to change the element’s background color.
Here is the HTML for the examples.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> button id="btn" style="background-color: salmon">Buttonbutton> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick(event) const backgroundColor = btn.style.backgroundColor; if (backgroundColor === 'salmon') btn.style.backgroundColor = 'green'; // 👇️ optionally change text color // btn.style.color = 'white'; > else btn.style.backgroundColor = 'salmon'; // 👇️ optionally change text color // btn.style.color = 'blue'; > >);
We added a click event listener to the button element, so a function is invoked every time the button is clicked.
In the function, we check if the element’s current background color is equal to a specific value and change it if it is.
If the element’s background color is not equal to the value, we reset the background color to its initial value.
You could add more conditions by using an else if statement.
Copied!const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick(event) const backgroundColor = btn.style.backgroundColor; if (backgroundColor === 'salmon') btn.style.backgroundColor = 'green'; > else if (backgroundColor === 'green') btn.style.backgroundColor = 'purple'; > else btn.style.backgroundColor = 'salmon'; > >);
In the example above the background colors of the element alternate between salmon , green and purple .
Note that instead of explicitly using btn , we can use the target property on the event object to access the element the user clicked on.
Copied!const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick(event) const backgroundColor = event.target.style.backgroundColor; if (backgroundColor === 'salmon') event.target.style.backgroundColor = 'green'; > else event.target.style.backgroundColor = 'salmon'; > >);
In the example, we used the target property on the event object. The target property is a reference to the object (element) on which the event was dispatched.