在锚标记中获取单词选择

Javascript: Get word selection in anchor tags

本文关键字:获取 单词 选择      更新时间:2023-09-26

我目前正在为chrome编写一个插件。我想通过使用热键+鼠标点击来选择单词。对于普通文本,我可以使用window.getSelection(),如下所示

    var s = window.getSelection();
s.modify('extend','backward','word');        
var firstPart = s.toString();
s.modify('extend','forward','word');
var lastPart = s.toString();
s.modify('move','forward','character');
var txt = firstPart + lastPart;

然而,它不工作,如果我尝试在一个链接中的单词。这行不通。如果有任何方法或javascript库,我可以使用它。

请帮帮我!

我认为问题可能是你正在使用一个onclick事件。我仍然不能100%确定您期望的行为,但我确实注意到使用onclickonmouseup之间有一个有趣的区别。我在JSFiddle中放置了一个演示:http://jsfiddle.net/EGmV3/1.

HTML:

<body>
    <p>Hold down 'F9' then select this text...</p>
    <p><a href="#">Now try it with this text..</a></p>
</body>
JavaScript:

var hotKeyIsDown = false;
window.onkeydown = function(ev) {
    hotKeyIsDown = false;
    if(ev.which === 120) //F9 key
        hotKeyIsDown = true;
}
window.onkeyup = function(ev) {
    hotKeyIsDown = false;
}
// try changing this to `window.onclick'
window.onmouseup = function (){
    if(hotKeyIsDown) {
        var s = window.getSelection();
        s.modify('extend','backward','word');        
        var firstPart = s.toString();
        s.modify('extend','forward','word');
        var lastPart = s.toString();
        s.modify('move','forward','character');
        var txt = firstPart + lastPart;
        alert("You were selecting '" + txt + "'");
        return false;
    }
}