首页 > 技术文章 > 好用的拖动脚本

relax 2013-08-15 11:39 原文

    以前使用Ext JS来搭界面没觉得拖动是件麻烦的事情,后来觉得Ext太大了,而且出了问题不好解决,简单的界面就自己来实现了。界面上经常要通过鼠标拖动改变大小,拖动无非是一些鼠标事件的实现。看了一些别人的脚本,自己总结了下弄了个简单的函数来实现.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>drad</title>

<script src="jquery.min.js"></script>
<script>
$(document).ready(function() {
    var div = document.getElementById('dragbar');
    bindResize(div);	//绑定拖动事件
});
function bindResize(el) {
    $(el).mousedown(function(e) {
        el.setCapture ? (
        el.setCapture(), el.onmousemove = function(ev) {
            mouseMove(ev || event)
        },
        el.onmouseup = mouseUp) : (
        $(document).bind("mousemove", mouseMove).bind("mouseup", mouseUp))
        e.preventDefault();
    });
    function mouseMove(e) {
        var maindiv_width = e.clientX;
        if (maindiv_width < 230) {
            maindiv_width = 230;
        }
        $('#maindiv').width(maindiv_width);	//拖动改变父DIV的宽度
    }
    function mouseUp() {
        el.releaseCapture ? (
        el.releaseCapture(), el.onmousemove = el.onmouseup = null) : (
        $(document).unbind("mousemove", mouseMove).unbind("mouseup", mouseUp));
    }
}
</script>
</head>

<body>
<div id="maindiv" style="width:300px; height:300px; background:#03C">
<div id="dragbar" style="width:7px; height:300px; float:right; background:#F00; cursor:w-resize;"></div>
</div>

</body>
</html>

  

 

演示效果:

推荐阅读