1

如何使用 jQuery 将click事件检测为双击?基本上,我希望.select类中的文本更容易选择,以便用户可以快速将内容复制到剪贴板。

<li>
    <span>
        Don't Select me
    </span>
    <span>
        Don't Select me
    </span>
    <span class="select">
        Select Me on click!
    </span>
</li>
4

1 回答 1

1

试试这个

function SelectText(element) {
    var doc = document;
    var text = doc.getElementById(element);    
    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();        
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

$(function() {
    $('.select').click(function() {
        SelectText('selectme');
    });
});​

https://stackoverflow.com/a/987376/1330581获取

示例http://jsfiddle.net/edelman/KcX6A/339/


更新:

选择同一个被点击元素的内容:

function SelectText(element) {
    var doc = document;
    var text = element;    
    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();        
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

$(function() {
    $('.select').click(function() {
        SelectText($(this)[0]); //Brackets are more efficiently that .get(0) method
    });
});​

示例:http: //jsfiddle.net/qBaWf/

于 2012-07-17T01:50:09.013 回答