如何点击或双击网页上的单词以触发事件处理程序? [英] how to make a click or double click on a word on a webpage to trigger an event handler?

查看:126
本文介绍了如何点击或双击网页上的单词以触发事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



http://www.answers .com



如果用户双击页面中的任何单词,弹出框将显示并显示该单词的定义。 p>

我可以想到一种方法来使用DOM脚本来分​​解页面中的所有单词,然后使它们分别在单独的span元素之下,但是否则是不是真的,如果所有的文本都在一个p元素,那么p元素节点被触发来处理双击事件,但没有简单的方法来告诉哪个单词被点击?

解决方案

您只需向整个文档添加双击事件,如下所示:

  function get_selection(){
var txt ='';
if(window.getSelection){
txt = window.getSelection();
} else if(document.getSelection){
txt = document.getSelection();
} else if(document.selection){
txt = document.selection.createRange()。text;
}
return txt;
}

$(document).dblclick(function(e){
var t = get_selection();
alert(t);
} );

如果您只希望这可以使用选择的段落,您可以将选择器更改为 p.myclass 或类似的东西。这取决于双击一个单词突出显示在浏览器中的事实。真的不知道如何answer.com这样做,说实话。


for a page like

http://www.answers.com

if the user double clicks on any word in the page, a pop up box will show up and shows the definition for that word.

I can think of a way to use DOM scripting to break up all words in the page and then make each of them go under a separate "span" element... but otherwise isn't it true that if all the text is under a "p" element, then the "p" element node get triggered to handle the double click event, but there is no easy way of telling which word is clicked on?

解决方案

You simply add a double click event to the entire document, like so:

function get_selection() {
    var txt = '';
    if (window.getSelection) {
        txt = window.getSelection();
    } else if (document.getSelection) {
        txt = document.getSelection();
    } else if (document.selection) {
        txt = document.selection.createRange().text;
    }
    return txt;
}

$(document).dblclick(function(e) {
    var t = get_selection();
    alert(t);
});

If you only wanted this to work on select paragraphs, you would change the selector to p.myclass or something like that. This hinges on the fact double clicking a word highlights it in browsers. Not really sure if it's exactly how answers.com does it, to be honest.

这篇关于如何点击或双击网页上的单词以触发事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆