How to get selected text from DIV using javascript ( working on IE7-8 )?
How to get highlighted text from DIV 开发者_运维技巧using javascript ?
Try this:
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection)
{
txt = document.getSelection();
}
else if (document.selection)
{
txt = document.selection.createRange().text;
}
else return;
Let's try.
<!DOCTYPE HTML>
<html>
<head>
<title>Highlighted text</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
if(!window.Kolich){
Kolich = {};
}
Kolich.Selector = {};
// getSelected() was borrowed from CodeToad at
// http://www.codetoad.com/javascript_get_selected_text.asp
Kolich.Selector.getSelected = function(){
var t = '';
if(window.getSelection){
t = window.getSelection();
}else if(document.getSelection){
t = document.getSelection();
}else if(document.selection){
t = document.selection.createRange().text;
}
return t;
}
Kolich.Selector.mouseup = function(){
var st = Kolich.Selector.getSelected();
if(st!=''){
alert("You selected:\n"+st);
}
}
$(document).ready(function(){
$(document).bind("mouseup", Kolich.Selector.mouseup);
});
</script>
</head>
<body>
Select some text on the page ...
</body>
</html>
You can customize the data of highlighted text on this function. The highlighted text is st
Kolich.Selector.mouseup = function () {
var st = Kolich.Selector.getSelected();
if (st != '') {
alert("You selected:\n" + st);
}
}
精彩评论