How to make a click or double click on a word on a web page to trigger an event handler?

佐手、 提交于 2019-12-03 07:32:18

问题


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?


回答1:


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.




回答2:


Here you go, a blog article that describes how you do this using jQuery. His test implementation is similar to what you want. Namely double clicking a word pulls up the definition from a dictionary:

Using jQuery and Double clicks to get data



来源:https://stackoverflow.com/questions/878637/how-to-make-a-click-or-double-click-on-a-word-on-a-web-page-to-trigger-an-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!