How to tell if a user has selected text on my page
I would like to know if someone has selected text on my page so I can 开发者_如何学Godisplay a context menu right where their cursor is. But I only want to display it if they have selected text by double-clicking the text. Is this possible?
I think it's possible because the same thing happens in I.E with that blue accelerator button thing.
Wouldn't this be enough?
http://jsfiddle.net/cLY8r/
Here's the code if you don't want to follow the link:
<div id="target">
Double-click here
</div>
<script type="text/javascript">
$('#target').dblclick(function() {
alert('Handler for .dblclick() called.');
});
</script>
I'm not sure about the double clicky thing.
But in IE i believe it is document.selection
i know in chrome it is document.getSelection()
.
This returns you a selection range object.
some light reading:
- http://help.dottoro.com/ljfjepre.php https://developer.mozilla.org/en/window.getSelection
A more robust solution that works in most browsers:
<div ondblclick="checkForSelectedText(this)">here is some text</div>
<script type="text/javascript">
function checkForSelectedText() {
var d = document;
var t;
// Modern browsers, including IE 6+
if (d && d.selection && d.selection.createRange) {
t = d.selection.createRange().text;
alert('createRange supported\n' + t);
// Others
} else if (d.getSelection) {
t = d.getSelection();
alert('getSelection supported\n' + d.getSelection());
}
return t;
}
</script>
However will not work inside elements like textarea or input for most browsers. Here's a more general version:
<div ondblclick="checkForSelectedText(event)">here is some text
<input value="and some inside an input">
<textarea>Lorem ipsum in a textarea</textarea>
</div>
<script type="text/javascript">
function checkForSelectedText(e) {
var el = e.target || e.srcElement;
var tagName = el.tagName && el.tagName.toLowerCase();
var t;
var d = document;
// Try DOM 2 Range - most browsers, including IE 6+
if (d && d.selection && d.selection.createRange) {
t = d.selection.createRange().text;
alert('createRange supported\n' + t);
// Otherwise try HTML5 - note that getSelection returns
// a string with extra properties
} else if (d.getSelection) {
t = d.getSelection();
alert('getSelection supported\n' +
'\n' + t);
}
// If didn't get any text, see if event was inside
// inupt@type=text or textarea
if (t == '') {
if (tagName == 'textarea' ||
(tagName == 'input' && el.type == 'text')) {
t = el.value.substring(el.selectionStart, el.selectionEnd)
alert('Inside ' + tagName + '\n' + t);
}
}
return t;
}
</script>
It may need a little more work for the case inside a form control, there should probably be tests for selectionStart and selectionEnd.
精彩评论