Css как сделать ползунок

Ползунок настраиваемого диапазона с использованием HTML, CSS и JavaScript

Вы узнаете, как создать ползунок настраиваемого диапазона с помощью HTML, CSS и JavaScript. Мы видим его на разных типах веб-сайтов электронной коммерции или на разных типах бизнес-сайтов. Этот тип ползунка диапазона HTML используется для выбора определенного значения в ползунке.

Это своего рода функция ввода HTML. HTML имеет много типов ввода, таких как текст, пароль, файл, ползунок и т. д. Этот тип ползунка настраиваемого диапазона имеет минимальное и максимальное значение. Пользователь может выбрать любое из этих значений.

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

Как создать ползунок настраиваемого диапазона с помощью HTML, CSS

Эмодзи в слайдере могут rotate 360 degrees . Эмодзи будет под углом 0 градусов при минимальном значении ползунка. Он будет вращаться, когда вы измените положение смайлика. Если вы новичок, то этот проект очень важен для вас.

Читайте также:  Python merge csv files

Сначала мы создали базовую структуру ползунка с помощью HTML. Затем для активации этого ползунка настраиваемого диапазона был использован JavaScript.

Этот ползунка можно использовать в дополнение к JavaScript. Однако для активации отображения важен JavaScript. Значение дисплея изменится, когда вы измените положение кнопки на ползунке.

Чтобы сделать этот настраиваемый ползунка диапазона, вам необходимо иметь базовое представление о HTML и CSS. Я представил демонстрацию, которая поможет вам узнать больше об этом ползунке настраиваемого диапазона.

Шаг 1. Базовая структура ползунка настраиваемого диапазона

Пришло время создать базовую структуру ползунка настраиваемого диапазона. Мы знаем, что ползунок настраиваемого диапазона создается с помощью функции ввода. Здесь я впервые создал ползунок настраиваемого диапазона, используя ввод и спроектированный с использованием некоторого количества CSS.

Таким образом, с помощью уровня была создана небольшая коробка. Всю информацию можно найти в этом поле. Это означает, что значение этого дисплея изменится, когда вы измените положение кнопки ползунка.

Шаг 2. Создайте дисплей для просмотра значений

Теперь я спроектировал уровень, т.е. следующие коды были использованы для разработки отображения представления значений. Я сделал небольшую коробку с белым фоном. Здесь используется синий цвет текста.

Шаг 3. Используйте изображения вместо кнопок-ползунков

Теперь ползунок настраиваемого диапазона разработан. Здесь использован прозрачный фон ползунка. Позже я использовал для этого другой фон. Здесь вместо кнопки «Ползунок диапазона» используется смайлик.

Как я уже говорил, смайлы использовались для придания красоты. Этот смайлик будет действовать как кнопка. Мы знаем, что в случае обычного ползунка диапазона кнопку можно перемещать. Здесь также значение диапазона будет изменено путем перемещения изображения.

Как упоминалось ранее, эта кнопка может rotate 360 . Но эта работа была сделана с помощью JavaScript.

input[type="range"] < -webkit-appearance: none; background: transparent; width: 90%; max-width: 500px; outline: none; >input[type="range"]:focus, input[type="range"]:active < border: 0; outline: none; >input[type="range"]::-webkit-slider-thumb < border: none; height: 40px; width: 40px; background-color: transparent; background-image: url("https://cdn.pixabay.com/photo/2020/09/14/18/34/amazed-5571740_1280.png"); background-position: 0 0; background-size: cover; transform: scale(1.9) rotateZ(var(--thumb-rotate, 10deg)); cursor: pointer; margin-top: -15px; -webkit-appearance: none; >
input[type="range"]::-webkit-slider-thumb:active

Шаг 4: Создайте работающую дорожку ползунка диапазона

Теперь этот ползунок создал беговую дорожку. Это означает, что фон слайдера был разработан. Фон выполнен в белом цвете, на котором будет продолжаться изображение.

input[type="range"]::-webkit-slider-runnable-track

Шаг 5. Активируйте ползунок настраиваемого диапазона с помощью JavaScript

Пришло время активировать отображение на этом слайде и расположить смайлики так, чтобы они вращались на 360 градусов. В результате изменение положения изображения изменит значение отображения. При этом смайлик будет вращаться на 360 градусов при каждом изменении.

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

const input = document.querySelector("input"); const label = document.querySelector("label"); input.addEventListener("input", event => < const value = Number(input.value) / 100; input.style.setProperty("--thumb-rotate", `$deg`); label.innerHTML = Math.round(value * 50); >); 

Надеюсь, из этого руководства вы узнали, как создать ползунок настраиваемого диапазона с помощью HTML, CSS и JavaScript.

Источник

Styling range input with CSS and JavaScript for better UX

To style the range input with CSS you’ll need to apply styles to two pseudo-elements: ::-webkit-slider-thumb and ::-webkit-slider-runnable-track . Find out how you can apply custom styling and make the range input more functional and appealing.

The input element with a type of range is a native HTML form UI element that allows users to select a value by dragging a slider over a range field.

The default browser styling for this element is very basic and doesn’t provide enough information to the user which might confuse one. Also, the appearance of the range input element is different across browsers.

Range input HTML:

Range input appearance on different browsers:

Range Input on Chrome Range Input on Edge Range Input on Firefox Range Input on Safari

Luckily there are ways you can improve that using nothing but native CSS and JavaScript.

Accent color

One simple way to customize the appearance of the range input without any specific selectors or additional HTML is to change the color of the range.

To do so you can define the accent-color property for the input[type=»range»] selector which will update the color of the track and thumb.

input[type="range"]  accent-color: coral; > 

CSS selectors for the range input

The range input widget consists of two parts the thumb and the track. Each one of these parts has its own pseudo-class selector for styling with a vendor suffix for cross-browser support.

input[type="range"]  -webkit-appearance: none; margin-right: 15px; width: 200px; height: 7px; background: rgba(255, 255, 255, 0.6); border-radius: 5px; background-image: linear-gradient(#ff4500, #ff4500); background-size: 70% 100%; background-repeat: no-repeat; > input[type="range"]::-webkit-slider-thumb  -webkit-appearance: none; height: 20px; width: 20px; border-radius: 50%; background: #ff4500; cursor: ew-resize; box-shadow: 0 0 2px 0 #555; transition: background .3s ease-in-out; > input[type=range]::-webkit-slider-runnable-track  -webkit-appearance: none; box-shadow: none; border: none; background: transparent; > 

To indicate the selected value, we can add a color from the start of the track up until the thumb. To do that we can use the background-image property with the linear-gradient() value. The background-size property will be used to set the size, which can later be updated with JavaScript.

Improving usability

The default range input doesn’t specify any values selected. Which makes it hard for users to understand what value is currently selected.

While the hash marks and labels on the range input are a great way to aid users visually, this feature is yet to become available.

However, there are a few ways you can improve that with some additional HTML and JavaScript:

  1. Specify the output element to display the selected value
  2. Specify the number input that is synced to the range input

Specify the output element to display the selected value

The output element on the side of the range input will display the selected value. You’ll have to add an id attribute for the output element, and an oninput attribute for the range input with a short function as a value, that will update the output element contents.

 type="range" min="0" max="100" oninput="rangevalue.value=value"/>  id="rangevalue">50 

Specify the number input that is synced to the range input

To take it a step further you can add a number input next to the range element.

That way the user will see the selected value and will have an option to modify it via the number input, which can be a better experience especially for mobile users.

 type="range" value="50" min="0" max="100" id="range" oninput="rangevalue.value=value"/>  type="number" id="rangevalue" value="50" oninput="range.value=value"> 

A sprinkle of JavaScript

To finalize we’ll need some JavaScript code to make it all work. The oninput attribute is already updating value based on a target element.

But to update the selected area of the range input we need to calculate the ratio and apply that value to the input background-size property.

💡 NOTE: the value property of the range input is a string type, if you want to use is as a numeric value you should use valueAsNumber property.

const rangeInputs = document.querySelectorAll('input[type="range"]') const numberInput = document.querySelector('input[type="number"]') function handleInputChange(e)  let target = e.target if (e.target.type !== 'range')  target = document.getElementById('range') > const min = target.min const max = target.max const val = target.value target.style.backgroundSize = (val - min) * 100 / (max - min) + '% 100%' > rangeInputs.forEach(input =>  input.addEventListener('input', handleInputChange) >) numberInput.addEventListener('input', handleInputChange) 

Range input for RTL direction

To make the above solution of custom range input work for RTL (right to left) web pages, you must make some adjustments for both CSS and JavaScript.

The recommended way to set the text direction of a block or a whole page is to use the dir attribute.

Once the dir attribute is set, we can specify the following selector for the range input [dir=»rtl»] input[type=»range»] .

Now to set the same value for the RTL direction, we must revet the background colors and the value. So for the 70% range, it will look as follows:

[dir="rtl"] input[type="range"]  /* Used to be gradient color, the current progress */ background: #ff4500; /* Used to be background color, the track */ background-image: linear-gradient(#fff, #fff); /* 30% is the difference between the max and the current value (100 - 70) */ background-size: 30% 100%; background-repeat: no-repeat; > 

As for the JavaScript, we need to add a condition for the change handler function, to calculate the correct value: max — current.

function handleInputChange(e)  let target = e.target if (e.target.type !== 'range')  target = document.getElementById('range') > const min = target.min const max = target.max const val = target.value let percentage = (val - min) * 100 / (max - min) // condition to check whether the document has RTL direction // you can move it to a variable, if document direction is dynamic if (document.documentElement.dir === 'rtl')  percentage = (max - val) > target.style.backgroundSize = percentage + '% 100%' > 

Custom range input Demo

You can find a full demo with a complete code examples on CodePen:

Источник

Оцените статью