开发者

JavaScript onHightlight?

Is there any event listener for highlight event in HTML usi开发者_StackOverflow社区ng JavaScript (sort of onHighlight)? Is it possible to get the text highlighted?


Try the following:

function getSelectedText() {
    if (window.getSelection) { // All browsers except IE <9
        return window.getSelection().toString();
    } else if (document.selection) { // IE <9
        return document.selection.createRange().text;
    }
}

All browsers (except for IE <9) support window.getSelection(); IE <9 supports document.selection.createRange().text.

The function can be attached to onmouseup, if you wish to support mouse-based selection, or onkeyup, if you wish to support keyboard-based selection.

As Robby Shaw mentions below, QuirksMode's Introduction to Range is fairly useful for understanding Range objects, which this code is based off.


No event handler for highlight, but you can write a function to check if anything is selected.

You can use document.getSelection() to check this.

If you want to highlight the specific text, you need to use range and document.selection to do it.

Please refer to http://www.quirksmode.org/dom/range_intro.html, it will help you to understand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜