如何使用焦点 select 文本 jquery
how to select text with jquery using focus
我正在尝试通过此代码 select 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
元素一起使用?
span
不像 input
那样工作,所以简短的回答是你不能那样做。默认情况下它甚至没有 focus
事件。
但有一个解决方法。您需要添加 tabindex="-1"
使其可聚焦并使用 window.getSelection().selectAllChildren(this);
到 select 它的值:
$(".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
我正在尝试通过此代码 select 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
元素一起使用?
span
不像 input
那样工作,所以简短的回答是你不能那样做。默认情况下它甚至没有 focus
事件。
但有一个解决方法。您需要添加 tabindex="-1"
使其可聚焦并使用 window.getSelection().selectAllChildren(this);
到 select 它的值:
$(".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