ham*_*boy 15 javascript textarea google-chrome
javascript函数使用.setSelectionRange()选择textarea中的某个单词.在Firefox中,textarea会自动向下滚动以显示所选文本.在Chrome(第14版)中,它没有.有没有办法让Chrome将textarea向下滚动到新选择的文本?jQuery解决方案欢迎.
这是一个简单而有效的解决方案,纯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对象的原型,你很好.
如果您需要任何进一步的帮助,请随时询问.
很多答案,但接受的没有考虑换行,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)
| 归档时间: |
|
| 查看次数: |
8356 次 |
| 最近记录: |