• Страница 1 из 1
  • 1
Форум » Веб-разработка » HTML + CSS — коды » Перестановка радиокнопон на JavaScript (Анимация ввода радиокнопки при клики на нее с эффектом)
Перестановка радиокнопон на JavaScript
Kosten
Вторник, 14 Июня 2022 | Сообщение 1
Оффлайн
Администраторы
Сообщений:44326
Награды: 70
Как мы можем создавать собственные и уникальные переключатели с помощью HTML CSS JavaScript. По сути, HTML -элементы input типа radio обычно используются в группах переключателей — наборах переключателей , описывающих или выбирающих опции. Одновременно может быть выбрана только одна радиокнопка в данной группе.

По умолчанию он поставляется с простыми черными и белыми маленькими кругами, но мы можем изменить стиль с помощью CSS и JS . Аналогично по умолчанию выбран первый вариант, а выбранная кнопка имеет красную рамку. Когда вы выберете любой другой вариант то активная кнопка переместится в это положение.



Установка:

html

Код
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Swappy Radio Inputs | Webdevtrick.com</title>
  <link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
  <link rel="stylesheet" href="style.css">

</head>
<body>

<div class="swappy-radios" role="radiogroup" aria-labelledby="swappy-radios-label">
  <h3 id="swappy-radios-label">Select An Option</h3>
  <label>
    <input type="radio" name="options" checked />
    <span class="radio"></span>
    <span>First Option</span>
  </label>
  <label>
    <input type="radio" name="options" />
    <span class="radio"></span>
    <span>Second Option</span>
  </label>
  <label>
    <input type="radio" name="options" />
    <span class="radio"></span>
    <span>Third Option</span>
  </label>
  <label>
    <input type="radio" name="options" />
    <span class="radio"></span>
    <span>Fourth Option</span>
  </label>
  <label>
    <input type="radio" name="options" />
    <span class="radio"></span>
    <span>Fifth Option</span>
  </label>
</div>

<script  src="function.js"></script>

</body>

css

Код
html {
  box-sizing: border-box;
  height: 100%;
  font-size: 10px;
}

*, *::before, *::after {
  box-sizing: inherit;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  color: #0f273d;
  font-family: 'Lato', sans-serif;
}

h3 {
  font-size: 2.5rem;
  font-weight: bold;
}

.swappy-radios label {
  display: block;
  position: relative;
  padding-left: 4rem;
  margin-bottom: 1.5rem;
  cursor: pointer;
  font-size: 2rem;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
  color: #555;
}
.swappy-radios label:hover input ~ .radio {
  opacity: 0.8;
}
.swappy-radios input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}
.swappy-radios input:checked ~ span {
  color: #ff4646;
  transition: color .5s;
}
.swappy-radios input:checked ~ .radio {
  background-color: #ff4646;
  opacity: 1 !important;
}
.swappy-radios input:checked ~ .radio::after {
  opacity: 1;
}
.swappy-radios .radio {
  position: absolute;
  top: 0;
  left: 0;
  height: 2.5rem;
  width: 2.5rem;
  background: #c9ded6;
}
.swappy-radios .radio::after {
  display: block;
  content: '';
  position: absolute;
  opacity: 0;
  top: 0.75rem;
  left: 0.75rem;
  width: 1rem;
  height: 1rem;
  background: #fff;
}

JavaScript

Код
let currentValue = 1;
const timeout = 0.75;
const radios = document.querySelectorAll('.swappy-radios input');
const fakeRadios = document.querySelectorAll('.swappy-radios .radio');

const firstRadioY = document.querySelector('.swappy-radios label:nth-of-type(1) .radio').getBoundingClientRect().y;
const secondRadioY = document.querySelector('.swappy-radios label:nth-of-type(2) .radio').getBoundingClientRect().y;
const indicitiveDistance = secondRadioY - firstRadioY;

fakeRadios.forEach(function(radio) {
  radio.style.cssText = `transition: background 0s ${timeout}s;`;
});

const css = `.radio::after {transition: opacity 0s ${timeout}s;}`
const head = document.head;
const style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(css));
head.appendChild(style);

radios.forEach(function(radio, i) {
  radio.parentElement.setAttribute('data-index', i + 1);
  
  radio.addEventListener('change', function() {
    temporarilyDisable();

    removeStyles();
    const nextValue = this.parentElement.dataset.index;

    const oldRadio = document.querySelector(`[data-index="${currentValue}"] .radio`);
    const newRadio = this.nextElementSibling;
    const oldRect = oldRadio.getBoundingClientRect();
    const newRect = newRadio.getBoundingClientRect();

    const yDiff = Math.abs(oldRect.y - newRect.y);
    
    const dirDown = oldRect.y - newRect.y > 0 ? true : false;
    
    const othersToMove = [];
    const lowEnd = Math.min(currentValue, nextValue);
    const highEnd = Math.max(currentValue, nextValue);

    const inBetweenies = range(lowEnd, highEnd, dirDown);
    let othersCss = '';
    inBetweenies.map(option => {

      const staggerDelay = inBetweenies.length > 1 ? 0.1 / inBetweenies.length * option : 0;
      othersCss += `
        [data-index="${option}"] .radio {
          animation: moveOthers ${timeout - staggerDelay}s ${staggerDelay}s;
        }
      `;
    });
    
    const css = `
      ${othersCss}
      [data-index="${currentValue}"] .radio {
        animation: moveIt ${timeout}s;
      }
      @keyframes moveIt {
        0% { transform: translateX(0); }
        33% { transform: translateX(-3rem) translateY(0); }
        66% { transform: translateX(-3rem) translateY(${dirDown ? '-' : ''}${yDiff}px); }
        100% { transform: translateX(0) translateY(${dirDown ? '-' : ''}${yDiff}px); }
      }
      @keyframes moveOthers {
        0% { transform: translateY(0); }
        33% { transform: translateY(0); }
        66% { transform: translateY(${dirDown ? '' : '-'}${indicitiveDistance}px); }
        100% { transform: translateY(${dirDown ? '' : '-'}${indicitiveDistance}px); }
      }
  `;
    appendStyles(css);
    currentValue = nextValue;
  });
});

function appendStyles(css) {
  const head = document.head;
  const style = document.createElement('style');
  style.type = 'text/css';
  style.id = 'swappy-radio-styles';
  style.appendChild(document.createTextNode(css));
  head.appendChild(style);
}
function removeStyles() {
  const node = document.getElementById('swappy-radio-styles');
  if (node && node.parentNode) {
    node.parentNode.removeChild(node);
  }
}
function range(start, end, dirDown) {
  let extra = 1;
  if (dirDown) {
      extra = 0;
  }
  return [...Array(end - start).keys()].map(v => start + v + extra);
}
function temporarilyDisable() {
    radios.forEach((item) => {
      item.setAttribute('disabled', true);
      setTimeout(() => {
        item.removeAttribute('disabled');
      }, timeout * 1000);
    });
}

Здесь JavaScript обрабатывает основную особенность программы, которая немного хитра и сложна. Сначала JS извлек данные с помощью document . querySelector и сохраняется в файле conts. По сути, JavaScript изменяет значения CSS в соответствии с действием, а не только имя класса, которое меняет все значения

Демонстрация
Прикрепления: 7315162.png (17.2 Kb) · option.zip (14.7 Kb)
Страна: (RU)
Форум » Веб-разработка » HTML + CSS — коды » Перестановка радиокнопон на JavaScript (Анимация ввода радиокнопки при клики на нее с эффектом)
  • Страница 1 из 1
  • 1
Поиск: