简体   繁体   中英

input event - losing focus while dragging input element

I'm trying to make a score module using a range input. I'm using the input event to achieve this. The range input works fine, but when I add event, it loses focus shortly after dragging begins.

This is how it looks:

截图

 document.querySelector("#score").addEventListener("input", e => { console.log(e.target.value); }); 
 <input type="range" min="1" max="10" value="10" draggable="true" class="score theme" id="score" step="0.1"> 

draggable="true" doesn't do what you think it does. An <input type="range"> has a draggable component to it by default. The draggable attribute makes it so that you can drag the entire element.

Removing this attribute gives the expected behaviour:

 document.getElementById('score').addEventListener('input', e => { console.log(e.target.value); }); 
 <input type="range" min="1" max="10" value="10" id="score" step="0.1"> 

That happens because you added draggable="true" to the element. So the behaviour is ambiguous, should the browser allow you to move the trackball or should the browser drag the element around the page?

The two behaviours are conflicting, so in the first moment it works properly as an input range and you're able to move it around, but then it allows you to drag the element.

What's your expected behaviour?

 document.querySelector("#score").addEventListener("input", e => { console.log(e.target.value); }); 
  <input type="range" min="1" max="10" value="10" class="score theme" id="score" step="0.1"> 

This seems to be a problem with the draggable="true" attribute and not the JavaScript code. The draggable attribute allows us to make the element draggable around the DOM, ie from one position to another in the viewport.

Therefore, when one tries to drag the range handle, the whole slider gets dragged along, instead of just the handle, which is what you described as "losing focus".

So, the solution is to simply remove the draggable=true attribute. I made a pen on CodePen to demonstrate this. https://codepen.io/aryan_02/pen/WPNBYm

Notice what the draggable attribute does. I hope this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM