使用javascript在单个左键单击中选择div中的所有文本 [英] selecting all text within a div on a single left click with javascript
问题描述
我在div中有一个简单的不可点击的链接,如下所示:
I have a simple non-clickable link within a div that looks like this:
这是一个可共享的链接,用户可以将粘贴复制到其他内容。
It's meant to be a sharable link that the user can copy paste into other things.
可用性目的,我想在div中的任意位置单击左键选择整个链接:
For usability purposes, I want a single left click anywhere within the div to select the entire link:
我对javascript / web编程了解不多,所以我尝试了以下内容:
I don't know much about, javascript/web programming, so I've tried the following:
<div id="share_link" onClick="select_all('share_link')"><%= request.url %></div>
此javascript
and this javascript
<script type="text/javascript">
function select_all(id) {
document.getElementById(id).focus();
}
</script>
这不起作用。我想知道为了实现我想要的东西,我应该做的最简单的事情是什么。我考虑过将div更改为文本输入或将文本更改为链接,但理想情况下,内容应该是只读的,不可编辑的,不可点击的
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
推荐答案
与其他浏览器相比,这在IE中完全不同。以下内容适用于所有主流浏览器:
This is achieved completely differently in IE compared to other browsers. The following will work in all major browsers:
<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>
这篇关于使用javascript在单个左键单击中选择div中的所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!