本文介绍了JavaScript:在Chrome中使用textarea.setSelectionRange后滚动到选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

以下是一个简单高效的解决方案,纯js:

  //首先,你忽略任何不好的英语,因为我是法语的,并且有一个有趣的晚上
//得到textarea
var textArea = document.getElementById('myTextArea');

//定义您的选择
var selectionStart = 50;
var selectionEnd = 60;
textArea.setSelectionRange(selectionStart,selectionEnd);

//现在让我们做一些数学
//我们需要一行中的字符数
var charsPerRow = textArea.cols;

//我们需要知道我们的选择在哪一行开始
var selectionRow =(selectionStart - (selectionStart%charsPerRow))/ charsPerRow;

//我们需要滚动到这一行,但滚动以像素为单位,
//所以我们需要知道一行的高度,以像素为单位
var lineHeight = textArea.clientHeight / textArea.rows;

//滚动!
textArea.scrollTop = lineHeight * selectionRow;

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

随意问你是否需要任何帮助。


A javascript function selects a certain word in a textarea using .setSelectionRange(). In Firefox, the textarea automatically scrolls down to show the selected text. In Chrome (v14), it does not. Is there a way to get Chrome to scroll the textarea down to the newly selected text? jQuery solutions welcome.

解决方案

Here is a simple and efficient solution, pure 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;

Put this in a function, extend the prototype of javascript's Element object with it, and you're good.

Feel free to ask if you need any further help.

这篇关于JavaScript:在Chrome中使用textarea.setSelectionRange后滚动到选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 23:43