javascript 使用javascript单击左键选择div中的所有文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4578398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
selecting all text within a div on a single left click with javascript
提问by tstyle
I have a simple non-clickable link within a div that looks like this:

我在 div 中有一个简单的不可点击链接,如下所示:

It's meant to be a sharable link that the user can copy paste into other things.
它是一个可共享的链接,用户可以将其复制粘贴到其他内容中。
For usability purposes, I want a single left click anywhere within the div to select the entire link:

出于可用性目的,我希望在 div 内的任意位置单击左键以选择整个链接:

I don't know much about, javascript/web programming, so I've tried the following:
我不太了解 javascript/web 编程,所以我尝试了以下方法:
<div id="share_link" onClick="select_all('share_link')"><%= request.url %></div>
and this javascript
和这个 javascript
<script type="text/javascript">
function select_all(id) {
document.getElementById(id).focus();
}
</script>
This doesn't work. I'd like to know what's the simplest thing I should do to achieve what I want. I thought about changing the div to a text input or the text within to be a link, but ideally the content within should be read-only, non-editable, and non-clickable
这不起作用。我想知道为了实现我想要的,我应该做的最简单的事情是什么。我想将 div 更改为文本输入或将其中的文本更改为链接,但理想情况下,其中的内容应为只读、不可编辑和不可点击
回答by Tim Down
This is achieved completely differently in IE compared to other browsers. The following will work in all major browsers:
与其他浏览器相比,这在 IE 中的实现方式完全不同。以下将适用于所有主要浏览器:
<script type="text/javascript">
function select_all(el) {
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.selection != "undefined" && typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.select();
}
}
</script>
<div onclick="select_all(this)">Link text</div>
回答by CamelCamelCamel
You can use jQuery for this with an input field:
您可以将 jQuery 与输入字段一起使用:
$("#myInputField").focus(function(){
// Select input field contents
this.select();
});
You can mask the fact that it is an input field using the readonly attribute in the html:
您可以使用 html 中的 readonly 属性掩盖它是一个输入字段的事实:
<input type="text" name="country" value="Norway"
readonly="readonly" />
And use CSS to change the cursor so it won't hint a text input, something like:
并使用 CSS 更改光标,使其不会提示文本输入,例如:
cursor: crosshair;

