【问题标题】:JavaScript: Stop the selection of a draggable elementJavaScript:停止选择可拖动元素
【发布时间】:2010-11-24 13:39:04
【问题描述】:

嘿,我只是在 jsFiddle 中搞乱,并试图进行简单的拖放。我没有费心得到偏移量等,所以只要你点击它就围绕着你的鼠标。在鼠标按下时,我返回 false,我认为这会阻止“幽灵”元素的出现。它没。我专注于鼠标向下的身体,以防万一,但它也没有帮助。

所以基本上我的问题是,我怎样才能停止选择元素?你可以在这里找到小提琴:http://jsfiddle.net/Wolfy87/HY2u4/

任何帮助将不胜感激。谢谢。

编辑:我刚刚在 safari 中测试过,没问题,目前看来只有 firefox。

【问题讨论】:

    标签: javascript drag-and-drop focus draggable


    【解决方案1】:
    jQuery.fn.extend({ 
      disableSelection : function() { 
        this.each(function() { 
          this.onselectstart = function() { return false; }; 
          this.unselectable = "on"; 
          jQuery(this).css('-moz-user-select', 'none'); 
        }); 
      } 
    }); 
    
    //How to use:
    $('div.draggable').disableSelection();
    

    没有 jQuery 的解决方案:

    function disableSelection(target){ 
      if (typeof target.onselectstart!="undefined") //IE route 
        target.onselectstart=function(){return false} 
      else if (typeof target.style.MozUserSelect!="undefined") //Firefox route 
        target.style.MozUserSelect="none" 
      else //All other route (ie: Opera) 
        target.onmousedown=function(){return false} 
        target.style.cursor = "default" 
    } 
    

    发现于:
    Is there a way to make text unselectable on an HTML page?

    【讨论】:

    • 抱歉,我没有使用 jQuery。这是我自己的图书馆。但是好的概念,将其粘贴在插件中。
    • 我发布了一个没有 jQuery 的解决方案
    • 谢谢你,+1。我想我会坚持我的,因为我更了解它。它有一个用于 IE,一个用于其余的。而不是 IE、Firefox 等。
    • 我会在您的 jQuery 解决方案中添加 jQuery(this).css({ '-moz-user-select' : 'none', '-webkit-user-drag' : 'none', '-webkit-user-select' : 'none' }); 以获得更广泛的浏览器支持。
    【解决方案2】:

    修复它。事实证明,我必须设置 onmousedown 和 onselectstart 函数。我认为这与在标签中放置onmousedown='...' 相同。不管怎样,现在已经修好了。只需转到小提琴页面即可。

    这基本上是修复它的代码。

    $('div.draggable').attribute().onselectstart = function () {
        return false;
    }
    
    $('div.draggable').attribute().onmousedown = function () {
        return false;
    }
    

    它会停止在 Firefox 和 IE 中将元素选择为文本的默认操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多