javascript函数使用.setSelectionRange()在textarea中选择某个单词.在Firefox中,文本区域自动向下滚动以显示所选文本.在Chrome(v14)中,没有.有没有办法让Chrome滚动文本区域到新选择的文本?欢迎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;
把它放在一个函数中,用它扩展javascript的Element对象的原型,你很好.
随时问你是否需要进一步的帮助.