【问题标题】:drag and drop, prevent awkward highlighting?拖放,防止尴尬的突出显示?
【发布时间】:2012-03-09 01:29:03
【问题描述】:

我正在构建一个拖放方法,使用查询 -onmousedown 导致 -onmousemove (drag) 然后 -onmouseup (unbinds onmousemove)

问题是,浏览器默认开始突出显示 onmousemove,它飞过整个页面并取消事件,使其无法使用。任何想法如何防止突出显示,因为 preventDefault 似乎不起作用。这是我的代码(是的,它非常草率,抱歉!)

$(".middleRow").mousedown(function(){
 calculateSelection();

  $('body').append('<div class="messageDrag" style="display:block">'+numSelected+'<div        style="font-size: 18px">messages</div></div>');


 $(document).mouseup(function(){

        $('.messageDrag').fadeOut(500);

        setTimeout(function(){
        $('.messageDrag').remove();
        }, 500);


        $(document).unbind();


    })


$(document).mousemove(function(e){


    e.preventDefault();


    var x = e.pageX;
    var y = e.pageY;
    $(".messageDrag").css("left", x-49);
    $(".messageDrag").css("top", y-49);


});

 });

【问题讨论】:

    标签: javascript jquery events drag-and-drop


    【解决方案1】:

    您可以使用 css 禁用突出显示

    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
    

    另一种方法是清除放置事件的选择,如下所示:

    function clearSelection() {
        var sel;
        if(document.selection && document.selection.empty){
            document.selection.empty() ;
        } else if(window.getSelection) {
            sel = window.getSelection();
            if(sel && sel.removeAllRanges)
            sel.collapse();
        }
    }
    

    所以你会在 drop 事件上调用clearSelection()(在拖动完成后)

    【讨论】:

    • 我不想完全删除突出显示,只有在这种拖动状态下。但我可以通过这样的查询将这个 css 放入,这是否有完整的浏览器支持?
    • 是的,它应该涵盖大多数现代浏览器(因此所有供应商前缀,甚至是 ms),您可以在初始化拖动时执行 $(element).css({// the css above});,并在拖放完成后将它们设置为 auto
    • hmm..这似乎并不能阻止突出显示,只是在视觉上摆脱它。更大的问题是突出显示的行为(当用户开始拖动文本时,会出现突出显示,或者如果在开始时他拖动它会取消拖动并开始突出显示)并且它正在破坏拖放。
    • 嗯好的,明白了...让我找出其他方法
    • 编辑了我的答案,请看看是否合适:)
    【解决方案2】:

    添加CSS

    -webkit-touch-callout: none;/*for mobile*/
    -webkit-user-select: none;/*for chrome*/
    -khtml-user-select: none;/*for safari*/
    -moz-user-select: none;/*for Mozilla*/
    -ms-user-select: none;/*for mircosoft*/
    -o-user-select: none;/*for opera*/
    user-select: none;/*base css ,but not work in all browsers*/
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      相关资源
      最近更新 更多