JavaScript:在Chrome中使用textarea.setSelectionRange后滚动到选择

ham*_*boy 15 javascript textarea google-chrome

javascript函数使用.setSelectionRange()选择textarea中的某个单词.在Firefox中,textarea会自动向下滚动以显示所选文本.在Chrome(第14版)中,它没有.有没有办法让Chrome将textarea向下滚动到新选择的文本?jQuery解决方案欢迎.

Mat*_*hen 7

您可以看到我们如何在ProveIt中解决问题(请参阅highlightLengthAtIndex).基本上,诀窍是截断textarea,滚动到结尾,然后恢复文本的第二部分.我们还使用textSelection插件来实现一致的跨浏览器行为.

  • 嗨Matt,只是建议,确实把代码放在你的答案中,这样我们就可以在SO而不是链接中看到它们. (9认同)

Fre*_*nié 7

这是一个简单而有效的解决方案,纯js:

//first of all, you ignore any bad english, as i'm french and had a funny evening
//get the textarea
var textArea = document.getElementById('myTextArea');

//define your selection
var selectionStart = 50;
var selectionEnd = 60;
textArea.setSelectionRange( selectionStart, selectionEnd);

// now lets do some math
// we need the number of chars in a row
var charsPerRow = textArea.cols;

// we need to know at which row our selection starts
var selectionRow = (selectionStart - (selectionStart % charsPerRow)) / charsPerRow;

// we need to scroll to this row but scrolls are in pixels,
// so we need to know a row's height, in pixels
var lineHeight = textArea.clientHeight / textArea.rows;

// scroll !!
textArea.scrollTop = lineHeight * selectionRow;
Run Code Online (Sandbox Code Playgroud)

把它放在一个函数中,用它扩展javascript的Element对象的原型,你很好.

如果您需要任何进一步的帮助,请随时询问.

  • `charsPerRow`逻辑忽略了换行符,包括软(在单词之间包装)和硬(实际换行符). (2认同)

Val*_*kov 6

很多答案,但接受的没有考虑换行,Matthew Flaschen没有添加解决方案代码,naXa答案有错误。最简单的解决代码是:

textArea.focus();

const fullText = textArea.value;
textArea.value = fullText.substring(0, selectionEnd);
textArea.scrollTop = textArea.scrollHeight;
textArea.value = fullText;

textArea.setSelectionRange(selectionStart, selectionEnd);
Run Code Online (Sandbox Code Playgroud)