bootstrap框架如何实现拖拽效果

2024年08月08日 建站教程

如何利用bootstrap框架做一个拖拽效果,下面web建站小编给大家详细介绍一下具体代码!

找到bootstrap.js源代码找到modal组件代码块的Modal.DEFAULTS代码下新增以下代码:

Modal.DEFAULTS = {
 backdrop: true,
 keyboard: true,
 show: true
}

//新加入的拖拽
Modal.prototype.draggable = function () {
 var $ele = this.$element;
 var mouseOffset;
 var $modalDialog = $ele.find(".modal-dialog");
 var dialogOffset;
  
 $ele.find(".modal-header").on('mousedown', function (event) {
   $(this).addClass({cursor: 'move'});
   $('body').addClass('select');
   dialogOffset = $modalDialog.offset();
   mouseOffset = {
      top: event.pageY - dialogOffset.top,
      left: event.pageX - dialogOffset.left
   };
   $('body').on("mousemove", function (event) {
      var left = event.pageX - mouseOffset.left;
      var top = event.pageY - mouseOffset.top;
      if (left < 10) { left = 0; } else if (left > $(window).width() - $modalDialog.width()) {
        left = $(window).width() - $modalDialog.width();
      }
      if (top < 10) { top = 0; } else if (top > $(window).height() - $modalDialog.height()) {
        top = $(window).height() - $modalDialog.height();
      }
      $modalDialog.offset({
        top: top,
        left: left
     });
   });
 });
  
 $(document).on("mouseup mouseleave", function () {
   $('body').off("mousemove");
 });
}

在modal的show方法中添加调用draggable方法

Modal.prototype.show = function (_relatedTarget) {
  var that = this
  var e = $.Event('show.bs.modal', {relatedTarget: _relatedTarget})
  
  this.$element.trigger(e)
  
  if (this.isShown || e.isDefaultPrevented()) return
  
  this.isShown = true
  
  //调用draggable()增加拖拽
  this.draggable()
  this.checkScrollbar()
  this.setScrollbar()
  this.$body.addClass('modal-open')
  
  this.escape()
  this.resize()
}

本文链接:http://so.lmcjl.com/news/10268/

展开阅读全文