Страницы

Поиск по вопросам

Показаны сообщения с ярлыком range. Показать все сообщения
Показаны сообщения с ярлыком range. Показать все сообщения

воскресенье, 2 февраля 2020 г.

Как получить значение input type=“range”

#javascript #html #input #range


Есть у меня :

У которого я двигаю бегунок. Как мне получить значение, текущего положения бегунка?


Ответы

Ответ 1



document.getElementById("myrange").addEventListener("change", function() { console.log(this.value); });

Ответ 2



Если использовать jQuery: $('.result').html($('input[type="range"]').val()); $(document).on('input change', 'input[type="range"]', function() { $('.result').html($(this).val()); }); .result { height: 30px; border:1px solid; margin: 2rem 0; width: 100px; }


вторник, 28 января 2020 г.

Замена элементов в листе по их индексу начиная с 1 а не 0

#python #list #список #range


Есть лист

list_1 = ['a', 'b', 'c']


Значения должны быть заменены таким образом

list_1 = ['element_1', 'element_2', 'element_3']


Начиная с 1 а не 0

Я пробовала так сделать

list_1 = ['element_{}'.format(i) for i in range(i+1, len(list_1))]


или так

list_1 = ['element_{}'.format(i) for i in range(1, len(list_1))]


Но если в листе 1 элемент возвращается пустой лист

list_2 = ['a']

    


Ответы

Ответ 1



На выбор: list_1 = ['element_{}'.format(i+1) for i in range(len(list_1))] list_1 = ['element_{}'.format(i) for i in range(1, len(list_1)+1)]

Ответ 2



for i in range(len(list_1)): # Проходим циклом по номерам списка list_1[i] = 'element_' + str(i + 1) # элементу списка с текущим номером присваиваем номер + 1, в виде строки

Ответ 3



Мне кажется для данной задачи более уместно использовать enumerate(iterable, start=1): >>> res = [f"element_{i}" for i,x in enumerate(list_1, 1)] >>> print(res) ['element_1', 'element_2', 'element_3'] PS именно для этих целей и была создана функция enumerate() ;-)

пятница, 24 января 2020 г.

Обращение к ползунку инпута range на js

#javascript #range


Нужен был слайдер для выбора цвета. Нашёл решение и немного изменил: https://codepen.io/hobuttt/pen/zLoyWx
Проблема в следующем: ползунок должен окрашиваться в выбранный цвет.
В найденном варианте используется: 

if (typeof InstallTrigger !== 'undefined') {
            var stylesheet = document.styleSheets[0];
            stylesheet.insertRule('input[type=range]::-moz-range-thumb { background:
' + bkgColor + ' }', stylesheet.cssRules.length);
        } else {
          document.styleSheets[0].addRule('input[type=range]::-webkit-slider-thumb',
'background-color: ' + bkgColor);
        }


Но в реале это не работает :


Обращение через querySelector тоже не срабатывает. 
Есть у кого-то варианты, как это можно решить?
    


Ответы

Ответ 1



Не вижу проблемы, код рабочий. При необходимости, добавьте правила для IE. Учтите также, что во всех браузерах, кроме префиксов, сильно разнится то, как применяются стили. Например, в Хроме border расположен внутри ползунка, а в Мозилле снаружи. // safari needs window.onload window.onload = function() { // create a element to hold the color gradient var canvas = document.createElement('canvas'); // range is 208-40=168, add 1 so range value stays inside the canvas canvas.width = 169; canvas.height = 1; // create a 2d context var canvasContext = canvas.getContext("2d"); // create linear gradient specify x,y,width,height var gradient = canvasContext.createLinearGradient(0, 0, canvas.width, canvas.height); // define colors to add - can use any color format but must be in quotes gradient.addColorStop(0, "#ff0000"); gradient.addColorStop(.17, "#ff00ff"); gradient.addColorStop(.33, "#0000ff"); gradient.addColorStop(.50, "#00ffff"); gradient.addColorStop(.67, "#00ff00"); gradient.addColorStop(.83, "#ffff00"); gradient.addColorStop(1, "#ff0000"); // use the gradient as a fill canvasContext.fillStyle = gradient; // draw the fill onto the canvas, specify x,y,width,height canvasContext.fillRect(0, 0, canvas.width, canvas.height); var thumb = document.getElementById("slider"); // updates the thumb colors while you drag the thumb, not sure why 'drag' event didn't work here thumb.addEventListener('mousemove', function() { changeColors(); }); // if 'mousemove' is too fast sometimes value and color won't // match up with thumb position, so update just in case thumb.addEventListener('change', function() { changeColors(); }); // display initial value var circle = document.getElementById("circle"); circle.innerHTML = thumb.value; // amount to increment/decrement // google's metronome uses 2, 3, and 4 steps var steps = 2; // decrement when minus is clicked var minus = document.getElementById("minus"); minus.addEventListener('click', function() { thumb.value = Number(thumb.value) - steps; changeColors(); }); // increment when plus is clicked var plus = document.getElementById("plus"); plus.addEventListener('click', function() { thumb.value = Number(thumb.value) + steps; changeColors(); }); // run it once to set colors changeColors(); // set the rgb values from using x, y coordinates function changeColors() { //range starts at 40 so subtract 40 var xCoord = thumb.value - 40; // get the color data from the canvas var rgbValues = canvas.getContext('2d').getImageData(xCoord, 0, 1, 1).data; var bkgColor = "rgb(" + rgbValues[0] + ", " + rgbValues[1] + ", " + rgbValues[2] + ")"; // display thumb value circle.innerHTML = thumb.value; // set colors circle.style.backgroundColor = bkgColor; minus.style.color = bkgColor; plus.style.color = bkgColor; // dynamically change color of thumb pseudo-element by adding new styles // test for Firefox API or else thumb won't change colors var stylesheet = document.styleSheets[0]; if (typeof InstallTrigger !== 'undefined') { stylesheet.insertRule('input[type=range]::-moz-range-thumb { border-color: ' + bkgColor + ' }', stylesheet.cssRules.length); } else { stylesheet.addRule('input[type=range]::-webkit-slider-thumb', 'border-color: ' + bkgColor); } } } #circle { width: 100px; height: 100px; border-radius: 50%; color: #FFF; font-weight: bold; font-family: sans-serif; font-size: 30px; text-align: center; line-height: 100px; } #slider { width: 420px; } #minus, #plus { font-weight: bold; font-size: 30px; cursor: pointer; -webkit-user-select: none; /* Chrome/Safari/Opera */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ } #slider { -webkit-appearance: none; -moz-appearance: none; outline: none; } #slider::-webkit-slider-runnable-track { width: 300px; height: 4px; background: linear-gradient(to left, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%); border: none; border-radius: 3px; margin-top: -15px; } #slider::-moz-range-track { width: 420px; height: 4px; background: linear-gradient(to left, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%); border: none; border-radius: 3px; margin-top: -15px; } #slider::-webkit-slider-thumb { -webkit-appearance: none; background: #fff; border-width: 4px; border-style: solid; height: 20px; width: 20px; border-radius: 50%; margin-top: -8px; } #slider::-moz-range-thumb { -moz-appearance: none; background: #fff; border-width: 4px; border-style: solid; height: 12px; width: 12px; border-radius: 50%; margin-top: -8px } canvas { border: solid 1px #f00; display: block; margin: 20px 0; }
− +
Ещё было замечено (в версиях браузеров более ранних, чем актуальные), что при стилизации нативных элементов, лучше использовать не общие свойства (например, border: width style color;), а разбивать на отдельные (border-width: ... и т.д.)

суббота, 16 марта 2019 г.

Обращение к ползунку инпута range на js

Нужен был слайдер для выбора цвета. Нашёл решение и немного изменил: https://codepen.io/hobuttt/pen/zLoyWx Проблема в следующем: ползунок должен окрашиваться в выбранный цвет. В найденном варианте используется:
if (typeof InstallTrigger !== 'undefined') { var stylesheet = document.styleSheets[0]; stylesheet.insertRule('input[type=range]::-moz-range-thumb { background: ' + bkgColor + ' }', stylesheet.cssRules.length); } else { document.styleSheets[0].addRule('input[type=range]::-webkit-slider-thumb', 'background-color: ' + bkgColor); }
Но в реале это не работает :
Обращение через querySelector тоже не срабатывает. Есть у кого-то варианты, как это можно решить?


Ответ

Не вижу проблемы, код рабочий. При необходимости, добавьте правила для IE. Учтите также, что во всех браузерах, кроме префиксов, сильно разнится то, как применяются стили. Например, в Хроме border расположен внутри ползунка, а в Мозилле снаружи.
// safari needs window.onload window.onload = function() { // create a element to hold the color gradient var canvas = document.createElement('canvas'); // range is 208-40=168, add 1 so range value stays inside the canvas canvas.width = 169; canvas.height = 1; // create a 2d context var canvasContext = canvas.getContext("2d"); // create linear gradient specify x,y,width,height var gradient = canvasContext.createLinearGradient(0, 0, canvas.width, canvas.height); // define colors to add - can use any color format but must be in quotes gradient.addColorStop(0, "#ff0000"); gradient.addColorStop(.17, "#ff00ff"); gradient.addColorStop(.33, "#0000ff"); gradient.addColorStop(.50, "#00ffff"); gradient.addColorStop(.67, "#00ff00"); gradient.addColorStop(.83, "#ffff00"); gradient.addColorStop(1, "#ff0000"); // use the gradient as a fill canvasContext.fillStyle = gradient; // draw the fill onto the canvas, specify x,y,width,height canvasContext.fillRect(0, 0, canvas.width, canvas.height); var thumb = document.getElementById("slider"); // updates the thumb colors while you drag the thumb, not sure why 'drag' event didn't work here thumb.addEventListener('mousemove', function() { changeColors(); }); // if 'mousemove' is too fast sometimes value and color won't // match up with thumb position, so update just in case thumb.addEventListener('change', function() { changeColors(); }); // display initial value var circle = document.getElementById("circle"); circle.innerHTML = thumb.value; // amount to increment/decrement // google's metronome uses 2, 3, and 4 steps var steps = 2; // decrement when minus is clicked var minus = document.getElementById("minus"); minus.addEventListener('click', function() { thumb.value = Number(thumb.value) - steps; changeColors(); }); // increment when plus is clicked var plus = document.getElementById("plus"); plus.addEventListener('click', function() { thumb.value = Number(thumb.value) + steps; changeColors(); }); // run it once to set colors changeColors(); // set the rgb values from using x, y coordinates function changeColors() { //range starts at 40 so subtract 40 var xCoord = thumb.value - 40; // get the color data from the canvas var rgbValues = canvas.getContext('2d').getImageData(xCoord, 0, 1, 1).data; var bkgColor = "rgb(" + rgbValues[0] + ", " + rgbValues[1] + ", " + rgbValues[2] + ")"; // display thumb value circle.innerHTML = thumb.value; // set colors circle.style.backgroundColor = bkgColor; minus.style.color = bkgColor; plus.style.color = bkgColor; // dynamically change color of thumb pseudo-element by adding new styles // test for Firefox API or else thumb won't change colors var stylesheet = document.styleSheets[0]; if (typeof InstallTrigger !== 'undefined') { stylesheet.insertRule('input[type=range]::-moz-range-thumb { border-color: ' + bkgColor + ' }', stylesheet.cssRules.length); } else { stylesheet.addRule('input[type=range]::-webkit-slider-thumb', 'border-color: ' + bkgColor); } } } #circle { width: 100px; height: 100px; border-radius: 50%; color: #FFF; font-weight: bold; font-family: sans-serif; font-size: 30px; text-align: center; line-height: 100px; } #slider { width: 420px; } #minus, #plus { font-weight: bold; font-size: 30px; cursor: pointer; -webkit-user-select: none; /* Chrome/Safari/Opera */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ } #slider { -webkit-appearance: none; -moz-appearance: none; outline: none; } #slider::-webkit-slider-runnable-track { width: 300px; height: 4px; background: linear-gradient(to left, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%); border: none; border-radius: 3px; margin-top: -15px; } #slider::-moz-range-track { width: 420px; height: 4px; background: linear-gradient(to left, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%); border: none; border-radius: 3px; margin-top: -15px; } #slider::-webkit-slider-thumb { -webkit-appearance: none; background: #fff; border-width: 4px; border-style: solid; height: 20px; width: 20px; border-radius: 50%; margin-top: -8px; } #slider::-moz-range-thumb { -moz-appearance: none; background: #fff; border-width: 4px; border-style: solid; height: 12px; width: 12px; border-radius: 50%; margin-top: -8px } canvas { border: solid 1px #f00; display: block; margin: 20px 0; }

− +

Ещё было замечено (в версиях браузеров более ранних, чем актуальные), что при стилизации нативных элементов, лучше использовать не общие свойства (например, border: width style color;), а разбивать на отдельные (border-width: ... и т.д.)