Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Помогите сделать динамическое изменение стилей фона на сайте (https://javascript.ru/forum/misc/73821-pomogite-sdelat-dinamicheskoe-izmenenie-stilejj-fona-na-sajjte.html)

Vadim Zhizherin 18.05.2018 16:10

Помогите сделать динамическое изменение стилей фона на сайте
 
Создайте HTML-страницу с возможностью переключения стилевого файла для страницы index.html.

Для этого необходимо создать две страницы со стилями light.css и dark.css', задающие разный фон и шрифт для страницы, а также к тегу <link>, с помощью которого подключается стилевой файл, добавить id:

<link id="CSSsource" href="light.css" rel="stylesheet" />
Далее нужно создать функцию, которая переключает стиль страницы при нажатии на кнопку.

Nexus 18.05.2018 16:24

var includeStyle;
(function() {
    const ID = 'variable-stylesheet';

    includeStyle = function(path) {//Принимает путь к css файлу
        let node = document.getElementById(ID);
        if (node)
            node.parentNode.removeChild(node);

        node = document.createElement('link');
        node.rel = 'stylesheet';
        node.href = path;
        node.id = ID;

        document.head.appendChild(node);
    };
})();

Vadim Zhizherin 18.05.2018 16:40

111111ывывывыв
 
Скажи, пожалуйста, где тут что? Как сделать так, чтобы по нажатию на кнопку менялся фон?

Nexus 18.05.2018 16:46

Vadim Zhizherin, функция "includeStyle" принимает в кач-ве аргумента строку (доступные значения: light, dark).

<button type="button" onclick="includeStyle('light.css');">Light</button>
<button type="button" onclick="includeStyle('dark.css');">Dark</button>

Vadim Zhizherin 18.05.2018 16:51

То есть там, где написано style писать light?
 
То есть там, где написано style писать light?

Должно быть две функции?

Nexus 18.05.2018 17:03

Vadim Zhizherin, я привел пример кнопок...

Vadim Zhizherin 18.05.2018 17:06

Я понял, но...
 
я понял, что функций две, но, там, где написано style или ID писать название css файла и его ID?

Vadim Zhizherin 18.05.2018 17:10

что не так? не робит :((
 
var includeStyle;
(function() {
    let styles = {
        light: 'light.css',
        dark: 'dark.css'
    };
    const ID = 'variable-stylesheet';

    includeStyle = function(light) {
        if (!styles[light])
            return;

        let node = document.getElementById(llight);
        if (node)
            node.parentNode.removeChild(node);

        node = document.createElement('light.css');
        node.rel = 'stylesheet';
        node.href = styles[light];
        node.id = llight;

        document.head.appendChild(node);
    };

      includeStyle = function(dark) {
        if (!styles[dark])
            return;

        let node = document.getElementById(ddark);
        if (node)
            node.parentNode.removeChild(node);

        node = document.createElement('dark.css');
        node.rel = 'stylesheet';
        node.href = styles[dark];
        node.id = ddark;

        document.head.appendChild(node);
    };
})();

Nexus 18.05.2018 17:12

Vadim Zhizherin, функция одна.
Убрал список доступных файлов, теперь функция принимает просто путь к css файлу.
Еще один пример:
<!-- Подключить файл «new-style.css» -->
<button type="button" onclick="includeStyle('new-style.css');">Подключить файл</button>

Nexus 18.05.2018 17:16

https://plnkr.co/edit/VhrGgdLyyI98sSbrmUNB?p=preview

Vadim Zhizherin 18.05.2018 17:25

Всё, спасибо, получилось
 
Всё, спасибо, получилось

рони 18.05.2018 17:40

:-?
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
  </style>
  <link id="CSSsource" href="light.css" rel="stylesheet" />
  <script>
      var n = 0;
      function changeStyle()
      {
         document.getElementById("CSSsource").href = ["light.css","dark.css"][++n%2]
      }
  </script>
</head>

<body>
<button type="button" onclick="changeStyle();" >изменить css</button>

</body>
</html>


Часовой пояс GMT +3, время: 07:16.