【问题标题】:how to select text with jquery using focus如何使用焦点选择带有jquery的文本
【发布时间】:2019-05-09 20:18:17
【问题描述】:

我正在尝试通过此代码选择 span 元素内的文本,但我没有成功:

<span class="selectme">this text should be selected by click</span> 

$(".selectme").live('focus', function() { $(this).select(); });

下面这个运行良好:

<input value="this text should be selected by click" class="selectme">

$("input.selectme").live('focus', function() { $(this).select(); });

如何使它与span 元素一起使用?

【问题讨论】:

    标签: javascript jquery html select focus


    【解决方案1】:

    span 不像input 那样工作,所以简短的回答是你不能那样做。默认情况下,它甚至没有 focus 事件。

    但是有一个解决方法。您需要添加tabindex="-1" 使其具有焦点并使用window.getSelection().selectAllChildren(this); 选择它的值:

    $(".selectme").on('focus', function() { 
        window.getSelection().selectAllChildren(this);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <span class="selectme" tabindex="-1">this text should be selected by click</span>

    Source

    同样live弃用,请改用on

    【讨论】:

      猜你喜欢
      • 2011-09-01
      • 1970-01-01
      • 2016-09-02
      • 2013-05-13
      • 2010-09-22
      • 2011-09-22
      相关资源
      最近更新 更多