HTML5 범위에 대한 onChange 이벤트
현재 내 범위 입력에 대한 onChange 이벤트가 각 단계에서 발생합니다.
사용자가 슬라이더를 놓을 때까지이 이벤트가 발생하지 않도록하는 방법이 있습니까?
범위를 사용하여 검색 쿼리를 만들고 있습니다. 양식이 변경 될 때마다 검색을 실행하고 싶지만 슬라이더 이동의 각 단계에서 검색 요청을 보내는 것이 너무 많습니다.
코드는 다음과 같습니다.
HTML :
<div id="page">
<p>Currently viewing page <span>1</span>.</p>
<input class="slider" type="range" min="1" max="100" step="1" value="1" name="page" />
</div>
자바 스크립트 :
$(".slider").change(function() {
$("#query").text($("form").serialize());
});
도움이 되나요?
최종 선택된 값에 사용 :
$(".slider").on("change", function(){console.log(this.value)});
슬라이딩으로 증분 값을 가져 오는 데 사용합니다.
$(".slider").on("input", function(){console.log(this.value)});
조금 늦었지만 다른 날에도 같은 문제가 발생했습니다. 다음은 jQuery bind / trigger를 사용하는 솔루션입니다.
(function(el, timeout) {
var timer, trig=function() { el.trigger("changed"); };
el.bind("change", function() {
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(trig, timeout);
});
})($(".slider"), 500);
이제 대신 '변경된'이벤트에 함수를 바인딩하십시오.
Bah!
onmouseup
대신 이벤트 사용onChange
한 가지 문제는 AFAIK가 HTML5에서 onchange
이벤트가 발생해야하는 시기를 정의하지 않기 때문에 브라우저마다 다를 가능성이 높다는 것입니다. 또한 브라우저가 실제로 input type=range
슬라이더 로 렌더링 할 필요가 없다는 점도 고려해야 합니다.
유일한 선택은 검색이 너무 자주 트리거되지 않도록 메커니즘을 구축해야한다는 것입니다. 예를 들어 검색이 현재 실행 중인지 확인하고 실행중인 경우 중단하거나 검색이 최대 x 초.
후자의 빠른 예 (테스트되지 않은 빠른 해킹).
var doSearch = false;
function runSearch() {
// execute your search here
}
setInterval(function() {
if (doSearch) {
doSearch = false;
runSearch();
}
}, 2000); // 2000ms between each search.
yourRangeInputElement.onchange = function() { doSearch = true; }
여기 Pure JS :
myInput.oninput = function(){
console.log(this.value);
}
또는
myInput.onchange = function(){
console.log(this.value);
}
gravediggin이지만 필요한 경우 js 스로틀 또는 디 바운스 기능을 확인하십시오.
용법:
//resize events gets processed 500ms after the last Event
addEventListener("resize", _debounce(function(){ foo;}, 500));
//resize events get processed every 500ms
addEventListener("resize", _throttle(function(){ foo;}, 500));
암호:
/*waits 'delay' time after the last event to fire */
_debounce = function(fn, delay) {
var timer = null;
return function() {
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
};
};
/* triggers every 'treshhold' ms, */
_throttle = function(fn, threshhold, scope) {
threshhold = threshhold || 250;
var last,
deferTimer;
return function() {
var context = scope || this;
var now = +new Date(),
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function() {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
};
Here's what I use for capturing the 'change event' for the html5 range slider:
HTML:
<form oninput="output1.value=slider1.value">
<input type="range" name="slider1" value="50"/>
<output name="output1" for="slider1">50</output>
</form>
JavaScript:
var $slider = $('input[name="slider1"]');
$slider.bind('change', function(e) {
e.preventDefault();
console.log($(this).val());
});
You can also bind the 'click' event to the range slider if you want to return its value when it has been clicked (or even dragged). Think of it like a 'mouseup' event. (I did try that but the slider didn't stop after I had clicked on the slider.)
JavaScript:
$slider.bind('click', function(e) {
e.preventDefault();
console.log($this).val());
}
On a side note, this returns a string so make sure you use 'parseInt($(this).value())' when appropriate.
Hope this helps.
I use several HTML5 default sliders in the same page with the following setup:
- Output tag in the page changes value when the slider is moved using the
oninput
event - A
change
event is triggered once on release
Tested with the latest Chrome and compiles well on a Raspberry with Node and Socket.io.
<output id="APIDConKpVal"></output> <input type="range"
class="PIDControlSlider"
min="0"
max="1500"
step="1"
id="APIDConKp"
oninput="APIDConKpVal.value=value"/>
<output id="APIDConKiVal"></output> <input type="range"
class="PIDControlSlider"
min="0"
max="2000"
step="1"
id="APIDConKi"
oninput="APIDConKiVal.value=value"/>
A simple Javascript code creates the listeners. You might need to try different events instead of 'change' in the last line to see what fits you.
window.onload=function()
{
var classname = document.getElementsByClassName("PIDControlSlider");
var myFunction = function() {
var attribute = this.getAttribute("id");
//Your code goes here
socket.emit('SCMD', this.getAttribute("id")+' '+ this.value);
};
for(var i=0;i<classname.length;i++){
classname[i].addEventListener('change', myFunction, false);
}
}
another suggest:
$(".slider").change(function(){
if (this.sliderTimeour) clearTimeout(this.sliderTimeour);
this.sliderTimeour = setTimeout(function(){
//your code here
},delayTimeHere);
});
You can try to use blur
event. Of course it also has it's limitations but it's just another suggestion :)
You can also try to combine the blur
, onkeyup
and onmouseup
events to try to catch different situations: blur
when the user makes the selection with keybord arrows and hits <Tab>
, onkeyup
when the user makes the selections with keyboard and stays focused on the slider, and onmouseup
when he uses the mouse. It might be even possible to only combine the onkeyup
and onmouseup
.
Still you will have to make a simple check if the value has changed or not and run neccessary code only after a change occured.
onchange works just fine , but I needed to update the value while sliding it.
var interval;
$("#rangeinput").mousedown(function(event){
interval = setInterval(function(){
$("#output").html($("#rangeinput").val());
console.log("running");
},150);
});
$("#rangeinput").mouseup(function(event){
clearInterval(interval);
});
Let's add a simple ES6 alternative to the collection:
let timer;
const debounceChange = (value, callback) => {
clearTimeout(timer);
timer = setTimeout(() => callback(value), 500);
};
When used in JSX it would look like this:
<input type="range" onChange={e => debounceChange(e.target.value, props.onChange)}/>
참고URL : https://stackoverflow.com/questions/5165579/onchange-event-for-html5-range
'Development Tip' 카테고리의 다른 글
WPF 응용 프로그램에서 사용자 설정을 저장하는 방법? (0) | 2020.11.11 |
---|---|
소켓 연결에 대한 추가 데이터 보내기 (0) | 2020.11.11 |
Rails : schema.rb의 기능은 무엇입니까? (0) | 2020.11.11 |
JSONP는 사용하기에 안전합니까? (0) | 2020.11.11 |
CSS로 배경 이미지 자르기 / 자르기 (0) | 2020.11.11 |