完美解决bootstrap模态框允许拖动后拖出边界的问题

使用bootstrap3版本

在网上看了很多方法,我觉得jquery-ui的实现方法是最简单有效的,具体实现方法

1.下载并引入jquery-ui插件

2.全局添加模态框允许拖动事件

$(document).on("show.bs.modal", ".modal", function(){
    $(this).draggable({
        handle: ".modal-header"   // 只能点击头部拖动
        cursor: 'move',
    });
    $(this).css("overflow", "hidden"); // 防止出现滚动条,出现的话,你会把滚动条一起拖着走的
});

这里记录一下bootstrap modal 的事件: 

show.bs.modal:在调用 show 方法后触发。

show.bs.modal:当模态框对用户可见时触发(将等待 CSS 过渡效果完成)。

hide.bs.modal:当调用 hide 方法时触发。

hidden.bs.modal:当模态框完全对用户隐藏时触发。

这种解决模态框拖动的方法还不完美,由于设置了只能点击头部拖动,经常出现下面这种拖动出页面边界后,点不到头部所以无法拖动回来的情况

jquery-ui中可以设置约束运动,即添加 $( element ).draggable({ containment: "parent" });

但是设置draggable的.modal元素宽高是100%,导致无法拖动。

所以需要修改一下,让拖动元素改为.modal下的.modal-dialog,但是.modal-dialog有个css属性 margin:30px auto 对横向拖动有影响,为此就想办法修改这个属性,网上让模态框竖向居中正好适合。

竖向居中的方法是修改bootstrap源码:

在bootstrap.js或bootstrap.min.js文件中找到Modal.prototype.show方法。

在that.$element.addClass('in').attr('aria-hidden', false)代码前加入下面这段代码。

that.$element.children().eq(0).css("position", "absolute").css({  
  "margin": "0px",  
  "top": function () {  
      return (that.$element.height() - that.$element.children().eq(0).height() - 40) / 2 + "px";  
  },  
  "left": function () {  
      return (that.$element.width() - that.$element.children().eq(0).width()) / 2 + "px";  
  }  
});

到这里就完美解决了!

$(document).on("shown.bs.modal", ".modal", function(){
    var dialog = $(this).find(".modal-dialog");
    dialog.draggable({
        handle: ".modal-header",   // 只能点击头部拖动
        cursor: 'move',
        refreshPositions: false,
        scroll: false,
        containment: "parent"
    });
    $(this).css("overflow", "hidden"); // 防止出现滚动条,出现的话,你会把滚动条一起拖着走的
});

猜你喜欢

转载自www.cnblogs.com/GaiaBing/p/9106341.html