在基于GET的文本区域中找到文本字符串,然后将光标移至该文本 [英] locate text string in textarea based on GET and move cursor to that text

查看:65
本文介绍了在基于GET的文本区域中找到文本字符串,然后将光标移至该文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表格中的文本区域id ="Fulltext"由数据库提供,包含一本书的许多章节. 当用户单击文本区域上方的链接时,
<a href="samePage.php?chap=Chapter 5" id="Chapter 5">Chapter 5</a>,我希望光标在文本区域内移动并将其自身定位在文本的第5章"前面. 这可能吗?

The textarea in my form, id="Fulltext", is fed by database with many chapters of a book. When the user clicks a link above the text area,
<a href="samePage.php?chap=Chapter 5" id="Chapter 5">Chapter 5</a>, I would like the cursor to move inside the textarea and position itself in front of the text, 'Chapter 5'. Is this possible?

推荐答案

演示: http://jsfiddle.net/deg6j/

HTML

<html>
<head>
    <script type="text/javascript">
        function selectText(text)
        {
            var textArea = $('#Fulltext');
            var index = textArea.text().search(text);
            textArea.caretTo(index);      
        }
    </script>
</head>
<body>
<textarea id='Fulltext' rows=10>
    Chapter 1
    This is a lot of text...

    Chapter 2
    More more more

    Chapter 3
    More dsa less
</textarea>
    <a href="#" onclick="selectText('Chapter 2')">Chapter 2</a>
</body>
</html>

JavaScript

Javascript

new function($) {
  // Behind the scenes method deals with browser
    // idiosyncrasies and such
    $.caretTo = function (el, index) {
        if (el.createTextRange) { 
            var range = el.createTextRange(); 
            range.move("character", index); 
            range.select(); 
        } else if (el.selectionStart != null) { 
            el.focus(); 
            el.setSelectionRange(index, index); 
        }
    };

    // The following methods are queued under fx for more
    // flexibility when combining with $.fn.delay() and
    // jQuery effects.

    // Set caret to a particular index
    $.fn.caretTo = function (index, offset) {
        return this.queue(function (next) {
            if (isNaN(index)) {
                var i = $(this).val().indexOf(index);

                if (offset === true) {
                    i += index.length;
                } else if (offset) {
                    i += offset;
                }

                $.caretTo(this, i);
            } else {
                $.caretTo(this, index);
            }

            next();
        });
    };
}(jQuery);

这篇关于在基于GET的文本区域中找到文本字符串,然后将光标移至该文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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