使用bootstrap3版本css
在网上看了不少方法,我以为jquery-ui的实现方法是最简单有效的,具体实现方法jquery
1.下载并引入jquery-ui插件bootstrap
2.全局添加模态框容许拖动事件ide
$(document).on("show.bs.modal", ".modal", function(){ $(this).draggable({ handle: ".modal-header" // 只能点击头部拖动
cursor: 'move', }); $(this).css("overflow", "hidden"); // 防止出现滚动条,出现的话,你会把滚动条一块儿拖着走的 });
这里记录一下bootstrap modal 的事件: ui
show.bs.modal:在调用 show 方法后触发。this
show.bs.modal:当模态框对用户可见时触发(将等待 CSS 过渡效果完成)。spa
hide.bs.modal:当调用 hide 方法时触发。prototype
hidden.bs.modal:当模态框彻底对用户隐藏时触发。插件
这种解决模态框拖动的方法还不完美,因为设置了只能点击头部拖动,常常出现下面这种拖动出页面边界后,点不到头部因此没法拖动回来的状况code
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"); // 防止出现滚动条,出现的话,你会把滚动条一块儿拖着走的 });