drag me

自己实现简单拖拽

by Three Tree

HTML

<div class="box">
    <h4 class="boxTitle">drag me1</h4>
    <p class="boxContent">
        内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料
    </p>
</div>

<div class="box">
    <h4 class="boxTitle">drag me2</h4>
    <p class="boxContent">
        内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料123123内容资料
    </p>
</div>

CSS

.box {
    position: absolute;
    margin: 10px;
    padding: 5px;
    width: 150px;
    height: 250px;
    border: 1px solid #6BAC46;
}
.boxTitle {
    padding-left: 5px;
    margin: 0;
    line-height: 24px;
    background-color: #4CCB00;
    cursor: move;
}
.boxContent {
    margin-top: 5px;
    height: 220px;
    background-color: #E9E9E9;
    word-break: break-all;
}

JavaScript

var $doc = $(document);
$doc.on('mousedown', '.boxTitle', function(e1) {
    var $this = $(this),
        $box = $this.parent(),
        o = $box.offset(),
        gapX = e1.clientX - o.left,
        gapY = e1.clientY - o.top;
    $doc.on('mousemove', function(e2) {
        $box.offset({left : e2.clientX - gapX, top : e2.clientY - gapY});
    });
}).on('mouseup', '.boxTitle', function() {
    $doc.off('mousemove');
});