type="range"

<input> element as "slider".

🔰 HTMLElements<input>

input vs. change event

oninput is similar to the onchange event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed.

簡單說,當我們拖曳滑桿的時候,隨時都會觸發 oninput 事件,但 onchange 事件是拖曳完放開滑鼠後才會觸發一次

const {log} = console;

const control = $('#control');
const div3 = $('#div3');
const label = $('#label');
const calc = $('#calc');

// marginControl.oninput
control.addEventListener('input', (e) => {
    let x = e.target.value;
    let percent = x + '%';
    label.textContent = 'marginTop: ' + percent;
    calc.textContent = `${percent} x 200px = ${2*x}px`
    div3.style.marginTop = percent;
});

// ⭐️ 自動跑一次 'oninput' event
control.dispatchEvent(new Event('input'));


// $ ⭐️ selector
function $(selector, parent = document){
  return parent.querySelector(selector);
}

Last updated