如何在textarea中选择文本行 [英] How to select line of text in textarea

查看:167
本文介绍了如何在textarea中选择文本行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个textarea,用于存放大量的SQL脚本进行解析。当用户单击Parse按钮时,他们会获得有关SQL脚本的摘要信息。

I have a textarea that is used to hold massive SQL scripts for parsing. When the user clicks the "Parse" button, they get summary information on the SQL script.

我希望摘要信息可以点击,以便在点击时, SQL脚本的行在textarea中突出显示。

I'd like the summary information to be clickable so that when it's clicked, the line of the SQL script is highlighted in the textarea.

我已经在输出中有行号,所以我需要的是javascript或jquery,告诉它要突出显示哪一行textarea。

I already have the line number in the output so all I need is the javascript or jquery that tells it which line of the textarea to highlight.

是否有某种类型的 goToLine 功能?在我所有的搜索中,没有什么能解决我正在寻找的问题。

Is there some type of "goToLine" function? In all my searching, nothing quite addresses what I'm looking for.

推荐答案

这个函数需要第一个参数来引用你的textarea和第二个参数是行号

This function expects first parameter to be reference to your textarea and second parameter to be the line number

function selectTextareaLine(tarea,lineNum) {
    lineNum--; // array starts at 0
    var lines = tarea.value.split("\n");

    // calculate start/end
    var startPos = 0, endPos = tarea.value.length;
    for(var x = 0; x < lines.length; x++) {
        if(x == lineNum) {
            break;
        }
        startPos += (lines[x].length+1);

    }

    var endPos = lines[lineNum].length+startPos;

    // do selection
    // Chrome / Firefox

    if(typeof(tarea.selectionStart) != "undefined") {
        tarea.focus();
        tarea.selectionStart = startPos;
        tarea.selectionEnd = endPos;
        return true;
    }

    // IE
    if (document.selection && document.selection.createRange) {
        tarea.focus();
        tarea.select();
        var range = document.selection.createRange();
        range.collapse(true);
        range.moveEnd("character", endPos);
        range.moveStart("character", startPos);
        range.select();
        return true;
    }

    return false;
}

用法:

 var tarea = document.getElementById('myTextarea');
 selectTextareaLine(tarea,3); // selects line 3

工作示例:

http://jsfiddle.net/5enfp/

这篇关于如何在textarea中选择文本行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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