I have a div ponent with an inner scrollbar and I'd like to prevent the up/down arrow keys from scrolling when the element is focused (mouse click on the element), as they are used for other events (e.g. zoom).
The only solution I found was to attach an event listener to the document, however, it disables all default arrow keys events, such as moving the cursor in an input field.
Here is an example (in React):
How to reproduce:
- Click with the mouse on the inner div (with the text)
- Click the down arrow key -> div scrolls down
Is there a way to prevent the scroll without disabling it on the document level?
Thanks!
UPDATE:
This missing piece was adding tab-index='0'
to the ponent (I updated the code above). Thanks @Jarvan
I have a div ponent with an inner scrollbar and I'd like to prevent the up/down arrow keys from scrolling when the element is focused (mouse click on the element), as they are used for other events (e.g. zoom).
The only solution I found was to attach an event listener to the document, however, it disables all default arrow keys events, such as moving the cursor in an input field.
Here is an example (in React): https://codesandbox.io/s/rsc-live-example-fze6z
How to reproduce:
- Click with the mouse on the inner div (with the text)
- Click the down arrow key -> div scrolls down
Is there a way to prevent the scroll without disabling it on the document level?
Thanks!
UPDATE:
This missing piece was adding tab-index='0'
to the ponent (I updated the code above). Thanks @Jarvan
- Seems your example is working, what is that you were not able to solve ? – Narkhede Tushar Commented Oct 24, 2019 at 5:13
- 1 @NarkhedeTushar when you click on the div and then the down arrow key it scrolls the div. I want to prevent that – Rani Commented Oct 24, 2019 at 5:43
1 Answer
Reset to default 4You can filter the events which you don't want to prevent, such as arrow event in input.
if (e.target.tagName.toLowerCase()!=="input" &&(e.key === "ArrowUp" || e.key === "ArrowDown")) {
e.preventDefault();
}
Then in input the cursor move will not be prevented.
But it won't work if the event you want to keep is some behavior in same element.
E.g. you have some children can be focus in the 'prevent arrow up/down scroll' div, you want to keep the ability to move focus between children by using arrow up/down. In that case I guess you have to implement you customize scrollbar then you have the full control, because in browser behavior I don't see a way to separate the single 'scroll' action.
Update:
If you know which ponent or area you want to effect, just add to that area. Like in your demo code:
<div tabindex="0"
onKeyDown={e => {
console.log(e);
if (e.key === "ArrowUp" || e.key === "ArrowDown") {
e.stopPropagation();
e.preventDefault();
console.log(e.key);
return false;
}
e.stopPropagation();
}}
>
{result}
</div>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745377893a4625085.html
评论列表(0条)