BLOGTOP

Информация о пользователе

Привет, Гость! Войдите или зарегистрируйтесь.


Вы здесь » BLOGTOP » Уголок wap мастера » JavaScript » Как сделать - Добавить активный класс к текущему элементу


Как сделать - Добавить активный класс к текущему элементу

Сообщений 1 страница 1 из 1

1

[html]<div id="myDIV">
  <button class="btn">1</button>
  <button class="btn active">2</button>
  <button class="btn">3</button>
  <button class="btn">4</button>
  <button class="btn">5</button>
</div>
<style>
/* Style the buttons */
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
}

/* Style the active class (and buttons on mouse-over) */
.active, .btn:hover {
  background-color: #666;
  color: white;
}
</style>
<script>
// Get the container element
var btnContainer = document.getElementById("myDIV");

// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}
</script>
[/html]

Шаг 1) добавить HTML:

Код:
<div id="myDIV">
  <button class="btn">1</button>
  <button class="btn active">2</button>
  <button class="btn">3</button>
  <button class="btn">4</button>
  <button class="btn">5</button>
</div>

Шаг 2) добавить CSS:

Код:
/* Style the buttons */
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
}

/* Style the active class (and buttons on mouse-over) */
.active, .btn:hover {
  background-color: #666;
  color: white;
}

Шаг 3) добавить JavaScript:

Код:
// Get the container element
var btnContainer = document.getElementById("myDIV");

// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}
Подпись автора

вопрос по ◆ВТ◆ в личку

вопрос по ◆ВТ◆ в тему

0

Быстрый ответ

Напишите ваше сообщение и нажмите «Отправить»


упс таблица

Откуда гость?
ВНИМАНИЕ! В подписи запрещены ссылки на конкурирующие сайты или форумы!


Вы здесь » BLOGTOP » Уголок wap мастера » JavaScript » Как сделать - Добавить активный класс к текущему элементу