Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Выбор нескольких условий одновременно (https://javascript.ru/forum/misc/77741-vybor-neskolkikh-uslovijj-odnovremenno.html)

Ruslantech 14.06.2019 05:39

Выбор нескольких условий одновременно
 
Я начинающий разработчик, столкнулся вот с такой проблемой: мне нужно применить одновременно несколько стилей для абзаца, но применяется только один и последний по выбору. Помогите кто сможет, заранее благодарен.

<!DOCTYPE html>
<html lang="ru">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>JavaScript</title>
    <style>
      
    </style>
  </head>
  <body>
    <ul>
      <p>Lorem ipsum dolor sit amet.</p>
      <input type="checkbox" value="text-decoration:line-through;"><span>перечеркнуть</span>
      <input type="checkbox" value="font-weight:bold;"><span>сделать жирным</span>
      <input type="checkbox" value="color:red"><span>сделать красным</span>
    <script>
      let text = document.querySelector('p')
      let input = document.querySelectorAll('input')
      for(var i = 0; i < input.length; i++){
        input[i].addEventListener('change', func)
      }

      function func(){
        if(this.checked){
          text.style.cssText = this.value
        }else{
          text.style.cssText = 'none'
        }
      }
    </script>
  </body>
</html>

рони 14.06.2019 10:13

Ruslantech,
строку cssText надо формировать в цикле, обходя все checked, и только потом менять style.
либо менять свойства style, а не style.cssText

рони 14.06.2019 10:18

Ruslantech,
<!DOCTYPE html>
<html lang="ru">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>JavaScript</title>
        <style>

        </style>
    </head>
    <body>

            <p>Lorem ipsum dolor sit amet.</p>
            <input type="checkbox" value="text-decoration:line-through;"><span>перечеркнуть</span>
            <input type="checkbox" value="font-weight:bold;"><span>сделать жирным</span>
            <input type="checkbox" value="color:red;"><span>сделать красным</span>
        <script>
            let text = document.querySelector('p')
            let input = document.querySelectorAll('input')
            for(var i = 0; i < input.length; i++){
                input[i].addEventListener('change', func)
            }

            function func(){
                var txt = '';
                for(var i = 0; i < input.length; i++){
                var el = input[i];
                if(el.checked) txt += el.value
                }
                text.style.cssText = txt
            }
        </script>
    </body>
</html>

MC-XOBAHCK 14.06.2019 10:39

Цитата:

Сообщение от Ruslantech (Сообщение 509036)
но применяется только один и последний по выбору.

Так вы задаёте стиль text.style.cssText = this.value
Собственно стиль назначается из value инпута на котором прошло событие.

Вариант через цикл forEach:
<!DOCTYPE html>
<html lang="ru">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>JavaScript</title>
        <style>
 
        </style>
    </head>
    <body>
 
            <p>Lorem ipsum dolor sit amet.</p>
            <input type="checkbox" value="text-decoration:line-through;"><span>перечеркнуть</span>
            <input type="checkbox" value="font-weight:bold;"><span>сделать жирным</span>
            <input type="checkbox" value="color:red;"><span>сделать красным</span>
        <script>
           let text = document.querySelector('p'),
            inputs = document.querySelectorAll('input');

        function textStyle() {
            let stl = '';

            inputs.forEach(el => el.checked ? stl += el.value : 0);

            text.style.cssText = stl;
        }

        inputs.forEach(el => el.addEventListener('input', textStyle));
        </script>
    </body>
</html>


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