欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jQuery实现拖拽效果插件的方法教程

程序员文章站 2022-06-21 19:29:46
本文实例讲述了jquery实现拖拽效果插件的方法。分享给大家供大家参考。具体如下: 下面的jquery插件允许你通过鼠标右键点击拖动overflow的元素,这个插件可以在移动设备...

本文实例讲述了jquery实现拖拽效果插件的方法。分享给大家供大家参考。具体如下:

下面的jquery插件允许你通过鼠标右键点击拖动overflow的元素,这个插件可以在移动设备上运行

/**
* jquery drag and scroll
*
* copyright (c) 2012 ryan naddy (ryannaddy.com)
* dual licensed under the mit and gpl licenses:
* https://www.opensource.org/licenses/mit-license.php
* https://www.gnu.org/licenses/gpl.html
*/
(function($){
  var down = false;
  var prevx = 0;
  var prevy = 0;
  var x = 0;
  var y = 0;
  var px = 0;
  var py = 0;
  var lastpx = -1;
  var lastpy = -1;
  var $target = null;
  var $me = null;
  var $selector = "";
  var settings = {
    mousebutton: 3,
    context: false,
    selecttext: false
  };
  $.fn.dragscroll = function(options){
    settings = $.extend(settings, options);
    $selector = $(this).selector;
    $(this).contextmenu(function(){
      return false;
    }).bind("mousedown touchstart", function(e){
      $me = $(this);
      e = event.touches ? event.touches[0] : e;
      $target = $(e.target);
      $target = $target.closest($selector);
      if(settings.viewport){
        if(!settings.context){
          $me.contextmenu(function(){
            return false;
          });
        }
      }
      if(!settings.selecttext){
        $me.attr('unselectable', 'on').css('user-select', 'none').on('selectstart', false);
      }
      $me = $me.closest($selector);
      if($target && $me.attr("id") != $target.attr("id")){
        return false;
      }
      if(e.which == settings.mousebutton || event.touches){
        $me.css("cursor", "move");
        down = true;
      }
      px = $me.scrollleft();
      py = $me.scrolltop();
      x = px + e.pagex;
      y = py + e.pagey;
      prevx = x;
      prevy = y;
      return true;
    }).bind("mouseup touchend", function(e){
      $me = $(this);
      e = event.touches ? event.touches[0] : e;
      $me.css("cursor", "auto");
      down = false;
    }).bind("mousemove touchmove", function(e){
      $me = $(this);
      $me = $me.closest($selector);
      e = event.touches ? event.touches[0] : e;
      if((e.which == settings.mousebutton || event.touches) && down){
        if(event.touches){
          event.preventdefault();
        }
        if($target && $me.attr("id") != $target.attr("id")){
          return false;
        }
        $me.css("cursor", "move");
        px = $me.scrollleft();
        py = $me.scrolltop();
        x = px + e.pagex;
        y = py + e.pagey;
        $me.scrollleft(px + (-(x - prevx)));
        $me.scrolltop(py + (-(y - prevy)));
        prevx = x - (x - prevx);
        prevy = y - (y - prevy);
        if(lastpx == px)
          prevx = x;
        if(lastpy == py)
          prevy = y;
        lastpx = px;
        lastpy = py;
      }
      return true;
    });
    return this;
  }
})(jquery);

希望本文所述对大家的jquery程序设计有所帮助。