文本选择(准备使用剪贴板操作)

Text select (ready to use clipboard operations)

本文关键字:剪贴板 操作 选择 文本      更新时间:2023-09-26

http://cdnjs.com/libraries/twitter-bootstrap/

在这个网站上,当我将鼠标悬停在给定文本的链接上时,选择了文本(如鼠标文本选择而不是 CSS 样式)。

我试图检查检查元素中的变化,我没有发现。

我试图找出JS或jQuery是否有方法来做到这一点。我找到了jquery的.select()方法,但它只能在表单元素上使用,并且jquery中没有deselect()方法,所以它肯定没有。

那么引擎盖下是什么?

更新:

我找到了这个解决方案我在JSFIDDLE中尝试过它,它工作得很好。但它是用 JS 编写的,带有 DOM 节点手稿,对我来说它看起来像希腊语和拉丁语。我无法编写此算法的jQuery版本。

.HTML:

<p id="selectable">hello</p>

.JS:

function fnSelect(objId) {
    fnDeSelect();
    if (document.selection) {
    var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(objId));
    range.select();
    }
    else if (window.getSelection) {
    var range = document.createRange();
    range.selectNode(document.getElementById(objId));
    window.getSelection().addRange(range);
    }
}
function fnDeSelect() {
    if (document.selection) document.selection.empty(); 
    else if (window.getSelection)
            window.getSelection().removeAllRanges();
}
$(document).ready(function(){
    $("p").on("mouseover",function(){
        var id = $(this).attr("id");
        fnSelect(id);
    });    
    $("p").on("mouseout",function(){
        fnDeSelect();
   });
});

发现这比它应该的要麻烦得多。 以下是您可以使用的内容:

来自 MDN:

window.getSelection().selectAllChildren(elementObject);

在这里找到的扩展研究(再次是MDN)

如果是我,我会这样做来达到效果:

function onMouseOver(e) {
    window.getSelection().selectAllChildren(e.currentTarget);
}
function onMouseOut(e) {
    window.getSelection().removeAllRanges(e.currentTarget);
}
document.getElementById("top").addEventListener("mouseenter", onMouseOver, false);
document.getElementById("top").addEventListener("mouseleave", onMouseOut, false);

现场演示:)