🔰 HTML🔰 element<input> type="range" <input> element as "slider".
🔰 HTML ⟩ Elements ⟩ <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 事件是拖曳完放開滑鼠後 才會觸發一次 。
JS CSS HTML
Copy 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);
}
Copy #div1 {
width : 200 px ;
border : 1 px solid black ;
}
#div2 , #div3 {
height : 100 px ;
}
#div2 {
/* ⭐️ vertical & horizontal align */
display : flex ;
justify-content : center ;
align-items : center ;
background-color : rgba (255 , 0 , 0 , 0.3) ;
font-weight : bold ;
}
#div3 {
margin-block-start : 10 % ;
background-color : rgba (0 , 255 , 21 , 0.3) ;
}
Copy <input type="range" id="control" min="-100" max="100" value="0">
<label for="marginControl" id="label"></label>
<p>
margin 若設定 %,則以「父元素寬度」為準。<br />
<span id="calc"></span>
</p>
<div id="div1">
<div id="div2">
<p>200 x 100</p>
</div>
<div id="div3"></div>
</div>