make bootstrap twitter dialog modal draggable

2019-03-08 10:29发布

I'm trying to make bootstrap twitter dialog modal draggable with this jquery plugin:

http://threedubmedia.com/code/event/drag#demos

but it doesn't work.

var $div = $('html');
console.debug($('.drag'));
$('#modalTest')
    .drag("start", function(ev, dd) {
        dd.limit = $div.offset();
        dd.limit.bottom = dd.limit.top + $div.outerHeight() - $(this).outerHeight();
        dd.limit.right = dd.limit.left + $div.outerWidth() - $(this).outerWidth();
    })
    .drag(function(ev, dd) {
        $(this).css({
            top: Math.min(dd.limit.bottom, Math.max(dd.limit.top, dd.offsetY))
            , left: Math.min(dd.limit.right, Math.max(dd.limit.left, dd.offsetX))
        });
    }); 

Have you idea how can I do it?

8条回答
孤傲高冷的网名
2楼-- · 2019-03-08 10:57

You can use the code below if you dont want to use jQuery UI or any third party pluggin. It's only plain jQuery.

$(".modal").modal("show");

$(".modal-header").on("mousedown", function(mousedownEvt) {
    var $draggable = $(this);
    var x = mousedownEvt.pageX - $draggable.offset().left,
        y = mousedownEvt.pageY - $draggable.offset().top;
    $("body").on("mousemove.draggable", function(mousemoveEvt) {
        $draggable.closest(".modal-dialog").offset({
            "left": mousemoveEvt.pageX - x,
            "top": mousemoveEvt.pageY - y
        });
    });
    $("body").one("mouseup", function() {
        $("body").off("mousemove.draggable");
    });
    $draggable.closest(".modal").one("bs.modal.hide", function() {
        $("body").off("mousemove.draggable");
    });
});
.modal-header {
    cursor: move;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div>

查看更多
\"骚年 ilove
3楼-- · 2019-03-08 10:57

use the jquery UI draggable, much simpler http://jqueryui.com/draggable/

查看更多
登录 后发表回答