如何在点击时选择跨度的文本?

MrV*_*mes 21 javascript jquery

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

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

<p>Fruit <span class="unc_path">\\apples\oranges\pears</span></p>
Run Code Online (Sandbox Code Playgroud)

我自己尝试实现这一点无济于事.

Eug*_*lov 41

它可以使用本机JavaScript实现.关于jsFiddle的工作演示.你的代码可能是这样的:

$('.unc_path').click(function (){
    var range, selection;

    if (window.getSelection && document.createRange) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(this);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if (document.selection && document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(this);
        range.select();
    }
});
Run Code Online (Sandbox Code Playgroud)


Bla*_*son 11

您可以使用CSS比JS更轻松地执行此操作 style="user-select: all;"

添加,cursor: pointer;这样很明显他们可以单击...

查看代码段:

<p>
Fruit 
<span style="user-select: all; cursor: pointer;">\\apples\oranges\pears</span>
</p>
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这个答案,尽可能使用CSS。 (2认同)

Den*_*ret 9

工作示范: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();
});?
Run Code Online (Sandbox Code Playgroud)

这个想法(见上面的评论)是用输入动态替换span,只有我知道选择文本的跨浏览器方式.

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

而且我还必须确切地说,与跨度相反的输入不能跨越多行.

我不认为这可以/应该在实际应用中使用,除非在一个非常具体的点上.


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

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

$('.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();
    });
});?
Run Code Online (Sandbox Code Playgroud)

  • 更好!我已经在我的页面中使用了这个(当焦点丢失时将其恢复正常的那个).再次感谢 :) (2认同)