29

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

例如,在下面的 html 片段中,我希望文本“\apples\oranges\pears”在单击时被选中。

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

我已经尝试自己实现这一点无济于事。

4

4 回答 4

49

它可以用原生 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();
    }
});
于 2013-02-11T16:35:05.717 回答
24

你可以使用 CSS 比 JS 更容易地做到这一点style="user-select: all;"

添加cursor: pointer;所以很明显他们可以点击...

见代码片段:

<p>
Fruit 
<span style="user-select: all; cursor: pointer;">\\apples\oranges\pears</span>
</p>

于 2018-11-30T00:58:33.637 回答
12

工作演示: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();
});​

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

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

而且我还必须指出,与跨度相反,输入不能跨越多行。

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


编辑:新版本: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();
    });
});​
于 2012-07-12T12:13:12.073 回答
0

要选择特定的 Span,您需要为该 Span 提供一个 id。否则,您需要遍历所有可用跨度的列表来获取它。

让我们以此为例(已添加 id 属性)

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

JQuery 会是这样的

$('span1').text()  // if you want to take the text
$('span1').html() // if you want to take the html
于 2012-07-12T12:03:32.060 回答