使用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"); // 防止出現滾動條,出現的話,你會把滾動條一塊兒拖着走的 });