8

Say I have an ul (li) list in the page:

<ul>
 <li>xxx<li>
 <li>xxx<li>
</ul>

The element li are clickable and double-clickable, they are attached with these events, and I return false in both of them.

$('ul li').on('click',function(){
    //do what I want
    return false;
}).on('dblclick',function(){
    //do what I want
    return false;
});

But when the user double-clicks the element, the text inside the li will be selected. How can this be prevented?

Update:

Solved now,I use the following code with the css selector by NiftyDude:

$('ul li').on('click',function(){
    //do what I want
    return false;
}).....on('dragstart',function(){return false;}).on('selectstart',function(){return false;});
4

2 に答える 2

19

You can disable text selection using css (Note that this will effectively disable all selection methods and not just double clicking)

ul li {
   -webkit-touch-callout: none;
   -webkit-user-select: none;
   -khtml-user-select: none;
   -moz-user-select: none;
   -ms-user-select: none;
   user-select: none;
}

http://jsfiddle.net/T3d7v/1/

于 2012-04-17T03:13:33.993 に答える
2

選択の発生を止めることはできませんが、選択が行われた直後に選択をクリアできます。

<script type="text/javascript">
document.ondblclick = function(evt) {
    if (window.getSelection)
        window.getSelection().removeAllRanges();
    else if (document.selection)
        document.selection.empty();
}
</script>

「トリプルクリック」で段落全体を選択しないようにするために、必要なコードは次のとおりです。

var _tripleClickTimer = 0;
document.ondblclick = function(evt) {
    ClearSelection();
    window.clearTimeout(_tripleClickTimer);

    //handle triple click selecting whole paragraph
    document.onclick = function() {
        ClearSelection();
    };

    _tripleClickTimer = window.setTimeout(function() {
           document.onclick = null; 
    }, 1000);
};

function ClearSelection() {
    if (window.getSelection)
        window.getSelection().removeAllRanges();
    else if (document.selection)
        document.selection.empty();
}

ソース/ライブ テスト

これはどのブラウザでも動作するはずです。動作しないブラウザを報告してください。

于 2012-04-17T03:38:50.807 に答える