简体   繁体   中英

Prevent scrolling to focused input/textarea element on change

I made a quick sandbox here for demonstration.

 const btn = document.querySelector("button") const topTextarea = document.querySelector("#input1") topTextarea.addEventListener("change", (e) => { e.preventDefault(); e.stopPropagation() }) topTextarea.addEventListener("keyup", (e) => { // e.preventDefault(); e.stopPropagation() }) topTextarea.addEventListener("keydown", (e) => { e.preventDefault(); e.stopPropagation() }) btn.addEventListener("click", () => { topTextarea.focus({ preventScroll: true }); })
 body { display: flex; justify-content: center; flex-direction: column; } textarea { height: 100px; } #demo { height: 3000px; }
 <textarea name="" id="input1" cols="30" rows="10">asdaasdasdsadasd</textarea> <div id="demo"></div> <button>Scroll Top element</button> <textarea name="" id="" cols="30" rows="10">Bottom</textarea>

Issue: Focus on any of textarea on page. Scroll out of them(while they are focused) then type something. Default behavior happens, page scrolls to the focused element.

In the sandbox you can see a button which triggers focus but prevents scroll.

Is it possible to implement so that when on change happens, we prevent scroll?

I found a solution.

Prevent keyDown event. Gather the entered char and update your 'state'.

And you can do some calculation and scroll to the element.

For my case scrollIntoView was causing issues with our design thats why i had to scroll manually.

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