如何选择点击范围内的文本? [英] How to select the text of a span on click?

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

问题描述

我正在寻找一种在单击文本时使用jquery在跨度内选择文本的方法.

I am looking for a way to select the text inside a span using jquery when the text is clicked on.

例如,在下面的html代码段中,我希望在单击文本时选择文本"\ apples \ oranges \ pears".

For example in the html snippet below, I want the text "\apples\oranges\pears" to become selected when it is clicked on.

<p>Fruit <span class="unc_path">\\apples\oranges\pears</span></p>

我尝试自己实施此操作无济于事.

I've tried implementing this myself to no avail.

推荐答案

工作示例: http://jsfiddle .net/dystroy/V97DJ/

$('.unc_path').click(function (){
    var text = $(this).text();
    var $input = $('<input type=text>');
    $input.prop('value', text);
    $input.insertAfter($(this));
    $input.focus();
    $input.select();
    $(this).hide();
});​

我的想法(请参阅上面的注释)是用输入动态替换跨度,这是我知道选择文本的唯一跨浏览器方式.

The idea (see comment above) is to dynamically replace the span with an input, only cross-browser way I know to have selected text.

请注意,这只是路的一半,因为您可能要取消选择,设置样式以删除边框等.

Note that this is only half the road, as you probably want to deselect, style to remove border, etc.

我还必须指出,与跨度相反,输入不能跨多行.

And I must also precise that an input, contrary to a span, cannot span on multiple lines.

除了非常特定的方面,我认为这不能/不应该在实际的应用程序中使用.

I don't think this could/should be used in a real application except in a very specific point.

编辑:新版本: http://jsfiddle.net/dystroy/A5ZEZ/

在此版本中,当焦点丢失时,文本会恢复正常.

In this version the text comes back to normal when focus is lost.

$('.unc_path').click(function (){
    var text = $(this).text();
    var $this = $(this);
    var $input = $('<input type=text>');
    $input.prop('value', text);
    $input.insertAfter($(this));
    $input.focus();
    $input.select();
    $this.hide();
    $input.focusout(function(){
        $this.show();
        $input.remove();
    });
});​

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

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