获取突出显示的文本 - 并导航到URL

时间:2012-01-12 21:58:27

标签: jquery

是否可以在div元素内的文本上抛出jquery-select()事件? 这是我的例子,但它不起作用。

<div id='id1'>Hello text</div>
$("#id1").select( function () { 
  alert("something was selected");
});

我的目标是在文本中选择一个单词,并将此选定的单词放在一个URL中,并使用此URL打开一个新窗口。 例如,我标记或者更确切地说我选择单词hello,单词hello应该在此URL中显示

window.open('http://dict.leo.org/ende?lp=ende&lang=de&searchLoc=0&cmpType=relaxed&sectHdr=on&spellToler=&search=Hello');

我不确定选择事件是否正确。 请帮忙。 抱歉我的英文不好!

2 个答案:

答案 0 :(得分:3)

翻译选定的(突出显示的)文本部分

<强> jsBin demo

function getSelRange() {
  var notIE8 = window.getSelection;
  var rng = notIE8 ? window.getSelection() : document.selection.createRange().htmlText;
  return $.trim(rng);
}

$('#id1').mouseup(function() {
  var selRange = getSelRange(); // THE HIGHLIGHTED TEXT PORTION
  if(selRange) window.open('https://translate.google.com/#en/de/'+ selRange); // TRANSLATE
});
<div id='id1'>
  Please highlight a text range you want to translate.
  Translating text is really cool. You should try it!
</div>

NB notIE8表示低于或等于IE8;)

P.S:如果您不使用jQuery并且需要支持旧浏览器,请确保使用onclick功能和a Polyfill for .trim();
否则像往常一样使用JS的addEventListener()String.prototype.trim()

答案 1 :(得分:2)

不,jQuery.select()仅限于文本输入字段和textareas。

javascript有多种选择:

if (window.getSelection) {
    txt = window.getSelection();
} else if (document.getSelection) {
    txt = document.getSelection();
} else if (document.selection) {
    txt = document.selection.createRange().text;
} else return;
alert(txt);

但是你必须将它绑定到某种监听器事件。大多数应用程序使用右键菜单或其他东西。