添加换行符后防止Chrome中的textarea滚动行为 [英] Preventing textarea scroll behaviour in chrome after newline added

查看:123
本文介绍了添加换行符后防止Chrome中的textarea滚动行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我的chrome版本做的事情越来越奇怪了(ubuntu 18.04上为74.0.3729.131).我有一个小的编辑器脚本,其中包含显示代码的文本区域.文本区域具有固定的大小和垂直滚动条.除此之外,别无他求.

Recently my version of chrome has been doing something strange (74.0.3729.131 on ubuntu 18.04) more and more often. I have a small editor script which has a textarea which displays code. The textarea has a fixed size and a vertical scroll bar. Beyond that nothing fancy.

通常,当我插入换行符(textarea的正常行为)时,滚动条不会移动.现在由于某种原因,它大约向下滚动文本区域80%的时间,直到插入标记的位置在文本区域的顶部.奇怪的是,如果我删除并在同一位置输入换行符,通常不会滚动.

Usually, when I insert a newline (normal behaviour of textarea), the scroll bar doesn't move. Now for some reason about 80% of the times it scrolls the textarea down till the position of the caret is at the top of the textarea. Strangely if I delete and enter the newline in the same position, it usually does not scroll.

我不确定这是否是Chrome中的一些新问题.使用相同的编辑器,以前的版本没有这个问题.

I'm not sure if this is some new issue in Chrome. I usen't have this issue with previous versions with the identical editor.

这里是一个演示问题的Codepen,滚动到某行,按Enter键,文本区域应向下滚动.尝试几次以查看不可预测的行为(添加代码只是为了能够添加链接,因为您看到的只是一个文本区域).

Here is a codepen which demonstrates the issue, scroll to some line, press enter and the textarea should scroll down. Try this a few times to see the unpredictable behaviour (adding the code just to be able to add the link, as you can see it's just a textarea).

https://codepen.io/anon/pen/rgKqMb

<textarea style="width:90%;height:300px"></textarea>

我想到的唯一避免此问题的解决方案是停止回车键的正常行为,并将换行符添加到文本中.任何其他想法/见解都非常欢迎.

The only solution that occurs to me to avoid this is to stop the normal behaviour of the enter key and add the newline to the text. Any other ideas/insights very much welcome.

推荐答案

您可以尝试使用css和js避免textarea上的事件,然后强制滚动到当前位置:

You can try avoiding the events on the textarea with css and js, then force the scroll to it's current position:

css:

textarea { 
    overflow:auto; 
    resize:none; 
    width:90%; 
    height:300px; 
} 

js: 您需要从此问题中插入第一个答案.在 A

js: You'll need to insert the first answer from this question at A

function preventMoving(e) {
    var key = (e.keyCode ? e.keyCode : e.which);
    if(key == 13) {
        e.preventDefault();
        // A
    }
}

然后在您的HTML上

<textarea onkeyup="preventMoving(event);"></textarea>

这篇关于添加换行符后防止Chrome中的textarea滚动行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆