Изменить цвет текста с помощью Switch/Toggle Css/javascript

Спасибо, что прочитали этот вопрос

  • На самом деле, я пытаюсь создать форму входа для ученика и учителя.
  • Где есть кнопка переключения/переключения между текстом учителя и ученика
  • Я хочу изменить цвет (скажем, на серый с зеленого) текста, когда переключатель переключается на соответствующий (учитель/ученик)
  • Например, если я нажал переключатель, а шарик-переключатель сместился вправо, это означает, что текст «Студент» будет серым и таким же для противоположной стороны.

Вот мой кодindex.html

.form-container{
            text-align: center;
            border-radius: 5px;
            background-color: #f6f6f6;
            padding: 30px 10px 30px 10px;
            margin: 0% 5% 0% 5%;
            font-family: 'Poppins', sans-serif;
            font-weight: 700;
            font-size: 30px;
            color: green;
            -webkit-box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
            -moz-box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
            box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
        }
        .input-design{
            margin: 0% 15% 0% 15%;
            margin-top: 50px;
        }
        .input-design input[type=text]{
            height: 50px;
            width: 100%;
            padding: 0px 0px 0px 10px;
            font-size: 20px;
            margin-bottom: 20px;
        }
        .input-design input[type=password]{
            height: 50px;
            width: 100%;
            padding: 0px 0px 0px 10px;
            font-size: 20px;
        }
        .button-design{
            padding: 15px 0px 0px 0px;
            height: 50px;
            font-weight: 600;
            font-size: 20px;
            margin: 5% 15% 5% 15%;
            background-color: green;
            color: white;
            border:1px solid white;
        }
        .button-design:hover{

            border:1px solid green;
            background-color: white;
            color: green;
        }

        .switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<body>
        <div class = "form-container">
            <div class = "role-selector">
                Teacher
                <label class = "switch">
                        <input type = "checkbox">
                        <span class = "slider round"></span>
                      </label>
                Student
            </div>
            <div class = "input-design">
                <input type = "text" name = "username" placeholder = "Username">
                <input type = "password" name = "password" placeholder = "Password">
            </div>
            <div class = "button-design">
                Login
            </div>
        </div>
    </body>
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
6
0
3 381
4
Перейти к ответу Данный вопрос помечен как решенный

Ответы 4

Вы должны переключить класс родительского div при изменении ввода, а затем установить цвет с этим именем класса.

document.getElementById('switch').addEventListener('click', function(event) {
  event.target.parentElement.parentElement.classList.toggle('student');
});
.form-container{
            text-align: center;
            border-radius: 5px;
            background-color: #f6f6f6;
            padding: 30px 10px 30px 10px;
            margin: 0% 5% 0% 5%;
            font-family: 'Poppins', sans-serif;
            font-weight: 700;
            font-size: 30px;
            color: green;
            -webkit-box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
            -moz-box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
            box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
        }
        .input-design{
            margin: 0% 15% 0% 15%;
            margin-top: 50px;
        }
        .input-design input[type=text]{
            height: 50px;
            width: 100%;
            padding: 0px 0px 0px 10px;
            font-size: 20px;
            margin-bottom: 20px;
        }
        .input-design input[type=password]{
            height: 50px;
            width: 100%;
            padding: 0px 0px 0px 10px;
            font-size: 20px;
        }
        .button-design{
            padding: 15px 0px 0px 0px;
            height: 50px;
            font-weight: 600;
            font-size: 20px;
            margin: 5% 15% 5% 15%;
            background-color: green;
            color: white;
            border:1px solid white;
        }
        .button-design:hover{

            border:1px solid green;
            background-color: white;
            color: green;
        }

        .switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

.role-selector {
  color: green;
}
 
.role-selector.student {
  color: grey;
} 
<body>
        <div class = "form-container">
            <div class = "role-selector">
                Teacher
                <label class = "switch">
                        <input id = "switch" type = "checkbox">
                        <span class = "slider round"></span>
                      </label>
                Student
            </div>
            <div class = "input-design">
                <input type = "text" name = "username" placeholder = "Username">
                <input type = "password" name = "password" placeholder = "Password">
            </div>
            <div class = "button-design">
                Login
            </div>
        </div>
    </body>

На самом деле вы можете поместить слово Учитель и ученик внутрь элемента span и присвоить ему идентификатор. И назначьте ID для входного переключателя для привязки к js function в onclick event.

.form-container{
            text-align: center;
            border-radius: 5px;
            background-color: #f6f6f6;
            padding: 30px 10px 30px 10px;
            margin: 0% 5% 0% 5%;
            font-family: 'Poppins', sans-serif;
            font-weight: 700;
            font-size: 30px;
            color: green;
            -webkit-box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
            -moz-box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
            box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
        }
        .input-design{
            margin: 0% 15% 0% 15%;
            margin-top: 50px;
        }
        .input-design input[type=text]{
            height: 50px;
            width: 100%;
            padding: 0px 0px 0px 10px;
            font-size: 20px;
            margin-bottom: 20px;
        }
        .input-design input[type=password]{
            height: 50px;
            width: 100%;
            padding: 0px 0px 0px 10px;
            font-size: 20px;
        }
        .button-design{
            padding: 15px 0px 0px 0px;
            height: 50px;
            font-weight: 600;
            font-size: 20px;
            margin: 5% 15% 5% 15%;
            background-color: green;
            color: white;
            border:1px solid white;
        }
        .button-design:hover{

            border:1px solid green;
            background-color: white;
            color: green;
        }

        .switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
        <div class = "form-container">
            <div class = "role-selector">
                <span class = "" id = "teacher">Teacher</span>
                <label class = "switch">
                        <input type = "checkbox" id = "toggle" onclick = "checkYesNo()">
                        <span class = "slider round"></span>
                      </label>
                <span class = "" id = "student">Student</span>
            </div>
            <div class = "input-design">
                <input type = "text" name = "username" placeholder = "Username">
                <input type = "password" name = "password" placeholder = "Password">
            </div>
            <div class = "button-design">
                Login
            </div>
        </div>
    </body>
    
    <script>
    function checkYesNo() {
        if (document.getElementById('toggle').checked) {
            document.getElementById('student').style.color = 'grey';
            document.getElementById('teacher').style.color = 'green';
        }else {
           document.getElementById('teacher').style.color = 'grey';
           document.getElementById('student').style.color = 'green';
        }
    }
    </script>

Большое спасибо, fms Third, сэр, за помощь с правильным кодом.

Santosh Kumar 25.06.2019 07:42

Использование элементов «до» и «после» вместо текста. Обновлен css внизу кода css. Не нужен jquery.

.form-container{
            text-align: center;
            border-radius: 5px;
            background-color: #f6f6f6;
            padding: 30px 10px 30px 10px;
            margin: 0% 5% 0% 5%;
            font-family: 'Poppins', sans-serif;
            font-weight: 700;
            font-size: 30px;
            color: green;
            -webkit-box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
            -moz-box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
            box-shadow: 5px 5px 5px -1px rgba(0,0,0,0.41);
        }
        .input-design{
            margin: 0% 15% 0% 15%;
            margin-top: 50px;
        }
        .input-design input[type=text]{
            height: 50px;
            width: 100%;
            padding: 0px 0px 0px 10px;
            font-size: 20px;
            margin-bottom: 20px;
        }
        .input-design input[type=password]{
            height: 50px;
            width: 100%;
            padding: 0px 0px 0px 10px;
            font-size: 20px;
        }
        .button-design{
            padding: 15px 0px 0px 0px;
            height: 50px;
            font-weight: 600;
            font-size: 20px;
            margin: 5% 15% 5% 15%;
            background-color: green;
            color: white;
            border:1px solid white;
        }
        .button-design:hover{

            border:1px solid green;
            background-color: white;
            color: green;
        }

        .switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

/* Input must be visible for before and after elements. Relative used for absolute position of children */

.switch input {
  position: relative;
}

/* Set text on before and after elements */

input::before,
input::after {
  font-family: 'Poppins', sans-serif;
  font-weight: 700;
  font-size: 30px;
}

input::before {
  position: absolute;
  left: 50px;
  bottom: 0;
  content: 'student';
}

input::after {
  position: absolute;
  right: 50px;
  bottom: 0;
  content: 'teacher';
}

/* Change colors based on checked status */

input:checked::before {
  color: green;
}

input:checked::after {
  color: grey;
}

input:not(:checked)::before {
  color: grey;
}

input:not(:checked)::after {
  color: green;
}
<body>
        <div class = "form-container">
            <div class = "role-selector">
                <label class = "switch">
                        <input type = "checkbox">
                        <span class = "slider round"></span>
                      </label>
            </div>
            <div class = "input-design">
                <input type = "text" name = "username" placeholder = "Username">
                <input type = "password" name = "password" placeholder = "Password">
            </div>
            <div class = "button-design">
                Login
            </div>
        </div>
    </body>

Спасибо, что ответили на мой вопрос, но ваш вывод отличается, пожалуйста, прокрутите вниз, чтобы увидеть fms Third, Dacre Denny

Santosh Kumar 25.06.2019 07:39
Ответ принят как подходящий

Если вы можете пересмотреть свой HTML, то это решение только для CSS также возможно:

/* CSS Additions */

/* Checkbox does not need to be displayed */
input {
  display: none;
}

/* Color labels green by default */
.role-selector input+span {
  color: green;
}
.role-selector input+*+*+span {
  color: grey;
}


/* Color labels when input is checked */
.role-selector input:checked+span {
  color: grey;
}
.role-selector input:checked+*+*+span {
  color: green;
}

/* --- */

.form-container {
  text-align: center;
  border-radius: 5px;
  background-color: #f6f6f6;
  padding: 30px 10px 30px 10px;
  margin: 0% 5% 0% 5%;
  font-family: 'Poppins', sans-serif;
  font-weight: 700;
  font-size: 30px;
  color: green;
  -webkit-box-shadow: 5px 5px 5px -1px rgba(0, 0, 0, 0.41);
  -moz-box-shadow: 5px 5px 5px -1px rgba(0, 0, 0, 0.41);
  box-shadow: 5px 5px 5px -1px rgba(0, 0, 0, 0.41);
}

.input-design {
  margin: 0% 15% 0% 15%;
  margin-top: 50px;
}

.input-design input[type=text] {
  height: 50px;
  width: 100%;
  padding: 0px 0px 0px 10px;
  font-size: 20px;
  margin-bottom: 20px;
}

.input-design input[type=password] {
  height: 50px;
  width: 100%;
  padding: 0px 0px 0px 10px;
  font-size: 20px;
}

.button-design {
  padding: 15px 0px 0px 0px;
  height: 50px;
  font-weight: 600;
  font-size: 20px;
  margin: 5% 15% 5% 15%;
  background-color: green;
  color: white;
  border: 1px solid white;
}

.button-design:hover {
  border: 1px solid green;
  background-color: white;
  color: green;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}



/*
Remove:
.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}
*/

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}



input:checked+span+.switch .slider {
  background-color: #2196F3;
}

input:focus+span+.switch .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+span+.switch .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}


/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<body>
  <div class = "form-container">
    <div class = "role-selector">
      <!-- Move input outside of .switch label -->
      <input type = "checkbox" checked id = "role-checkbox">
      <span>Teacher</span>
      <!-- Add for attribute that matches id of check input -->
      <label class = "switch" for = "role-checkbox">
                  <span class = "slider round"></span>
                </label>
      <span>Student</span>
    </div>
    <div class = "input-design">
      <input type = "text" name = "username" placeholder = "Username">
      <input type = "password" name = "password" placeholder = "Password">
    </div>
    <div class = "button-design">
      Login
    </div>
  </div>
</body>

Большое спасибо, Дакре Денни, сэр, за помощь с вашим правильным кодом и более удобным для пользователя.

Santosh Kumar 25.06.2019 07:43

Другие вопросы по теме