Hammer.js 移动端手势库,多点触控插件

 jquery用法:

引入3个JS:
<script src="jquery.js"></script> <script src="hammer.js"></script> <script src="jquery.hammer.js"></script>
$(".myElement").hammer().bind("tap", function(ev) {
            $(this).addClass("red");
            console.log(ev);
        }).bind("press", function(ev) {
            $(this).removeClass("red");
            console.log("press");
        });
//下面写在一起

拖动:

 <div id="myElement" style="position:fixed;"> </div>

 var getCss = function(o,key){
            return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key];
        };

        function drag(element){
            element.style.top = getCss(element,"top");
            element.style.left = getCss(element,"left");
            var hammer = new Hammer(element);//hammer实例
            var x = 0;
            var y = 0;
            hammer.on('panstart',function(event){
                console.log("panstart");
                x = parseInt(element.style.left);
                y = parseInt(element.style.top);
            });
            hammer.on('panmove',function(event){
                console.log("panmove");
                element.style.top = y + event.deltaY + "px";
                element.style.left = x + event.deltaX + "px";
            });
            hammer.on('panend',function(event){
                console.log("panend");
            });
        }
        var myElement = document.getElementById("move-box");
        drag(myElement);

 

一般用法:

 <script src="hammer.js"></script>

        var myElement = document.getElementById('myElement');
        var mc = new Hammer(myElement);

        mc.get('pan').set({ direction: Hammer.DIRECTION_ALL });
        mc.on("panleft panright panup pandown tap press", function(ev) {
            if(ev.type == "press"){
                obj.addClass("red")                
            }else {
                obj.removeClass("red");
            }
        });

 

 

 

官网:

http://hammerjs.github.io/

 

在线调试:

http://codepen.io/jtangelder/pen/lgELw

 

 

网上:

http://www.tuicool.com/articles/VNRjym7

http://blog.csdn.net/kongjiea/article/details/43016085

 

 



 


 -----------------   原生JS:


 

JS拖拽移动位置(手机端)

<div id="div" style="width:100px;height:100px;background-color:red;position:absolute;"></div>
<script>
    var div = document.getElementById('div');
    div.addEventListener('touchmove', function(event) {
        event.preventDefault();//阻止其他事件
        // 如果这个元素的位置内只有一个手指的话
        if (event.targetTouches.length == 1) {
            var touch = event.targetTouches[0];  // 把元素放在手指所在的位置
            div.style.left = touch.pageX + 'px';
            div.style.top = touch.pageY + 'px';
            div.style.background = "green";
        }
    }, false);
</script>
View Code

 

JQUERY手机长按触发事件(手机端)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" Content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0">
    <title>fdsa</title>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
    <div id="div" style="width:100px;height:100px;background:#ddd;position:absolute;"></div>
    <script>
        //长按事件
        $.fn.longPress = function (fn) {
            var timeout = undefined;
            var $this = this;
            for (var i = 0; i < $this.length; i++) {
                $this[i].addEventListener('touchstart', function (event) {
                    timeout = setTimeout(fn, 500);
                }, false);
                $this[i].addEventListener('touchend', function (event) {
                    clearTimeout(timeout);
                }, false);
            }
        };

        //阻止浏览器 复制粘贴等事件
        window.ontouchstart = function (e) { e.preventDefault(); };

        //触发事件
        $("#div").longPress(function () {
            console.log("long");
            alert("Ok");
        });
    </script>
</body>
</html>
View Code

 

JQUERY手机长按并移动触发事件(手机端)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" Content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0">
    <title>长按并移动</title>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <style>
        .mydiv{
            position:absolute;
            left:10px;
            top:10px;
            background-color:gray;
            width:100px;
            height:80px;
            z-index:10;
            display:block;
        }
    </style>
</head>

<body>

<div class="mydiv">out</div>
<div class="mydiv" style="top:200px;">out</div>

<script>
    $.fn.longPress = function (fn) {

        /*设置一个长按的计时器,如果点击这个图层超过2秒则触发,mydiv里面的文字从out变in的动作*/
        var timeout = undefined;
        var state = 0;

        var $this = this;
        for (var i = 0; i < $this.length; i++) {
            $this[i].addEventListener('touchstart', function (event) {

                clearTimeout(timeout);
                state = 0;
                timeout = setTimeout(function () {
                    state = 1;
                }, 1000);

            }, false);

            $this[i].addEventListener('touchmove', function (event) {

                if (state == 1) {
                    console.log("move");
                }

            }, false);

            $this[i].addEventListener('touchend', function (event) {

                clearTimeout(timeout);

                if (state == 1) {
                    console.log("end");
                    state = 0;
                }


            }, false);

        }

    };

    //阻止浏览器 复制粘贴等事件
    window.ontouchstart = function (e) {
        e.preventDefault();
    };

    //触发事件
    $(".mydiv").longPress(function () {

        console.log("long");

    });


</script>
</body>
</html>
View Code

 

 

JS拖拽交换位置(电脑端)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>孚盟CRM</title>
    <meta name="viewport" Content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0">


    <title></title>
    <style type="text/css">
        *{ margin: 0; padding: 0; -moz-user-select:none;}
        ul{ margin: 100px; border: 1px solid #adff2f; list-style: none;}
        li{ height: 30px; line-height: 30px; padding: 0; list-style: none;}
        li:hover{ background: #bdb76b; cursor: move;}
    </style>
</head>
<body>

<ul id="outer_wrap">
    <li>第一条</li>
    <li>第二条</li>
    <li>第三条</li>
    <li>第四条</li>
    <li>第五条</li>
    <li>第六条</li>
    <li>第七条</li>
    <li>第八条</li>
</ul>

<script type="text/javascript">
    function $(id){
        return document.getElementById(id);
    }
    //获取鼠标位置
    function getMousePos(e){
        return {
            x : e.pageX || e.clientX + document.body.scrollLeft,
            y : e.pageY || e.clientY + document.body.scrollTop
        }
    }
    //获取元素位置
    function getElementPos(el){
        return {
            x : el.offsetParent ? el.offsetLeft + arguments.callee(el.offsetParent)['x'] : el.offsetLeft,
            y : el.offsetParent ? el.offsetTop + arguments.callee(el.offsetParent)['y'] : el.offsetTop
        }
    }
    //获取元素尺寸
    function getElementSize(el){
        return {
            width : el.offsetWidth,
            height : el.offsetHeight
        }
    }
    //禁止选择
    document.onselectstart = function(){
        return false;
    }
    //判断是否有挪动
    var MOVE = {};
    MOVE.isMove = false;

    //就是创建的标杆
    var div = document.createElement('div');
    div.style.width = '400px';
    div.style.height = '1px';
    div.style.fontSize = '0';
    div.style.background = 'red';

    var outer_wrap = $('outer_wrap');
    outer_wrap.onmousedown = function(event){
//获取列表顺序
        var lis = outer_wrap.getElementsByTagName('li');
        for(var i = 0; i < lis.length; i++){
            lis[i]['pos'] = getElementPos(lis[i]);
            lis[i]['size'] = getElementSize(lis[i]);
        }
        event = event || window.event;
        var t = event.target || event.srcElement;
        if(t.tagName.toLowerCase() == 'li'){
            var p = getMousePos(event);
            var el = t.cloneNode(true);
            el.style.position = 'absolute';
            el.style.left = t.pos.x + 'px';
            el.style.top = t.pos.y + 'px';
            el.style.width = t.size.width + 'px';
            el.style.height = t.size.height + 'px';
            el.style.border = '1px solid #d4d4d4';
            el.style.background = '#d4d4d4';
            el.style.opacity = '0.7';
            document.body.appendChild(el);

            document.onmousemove = function(event){
                event = event || window.event;
                var current = getMousePos(event);
                el.style.left =t.pos.x + current.x - p.x + 'px';
                el.style.top =t.pos.y + current.y - p.y+ 'px';
                document.body.style.cursor = 'move';

//判断插入点
                for(var i = 0; i < lis.length; i++){
                    if(current.x > lis[i]['pos']['x'] && current.x < lis[i]['pos']['x'] + lis[i]['size']['width'] && current.y > lis[i]['pos']['y'] && current.y < lis[i]['pos']['y'] + lis[i]['size']['height']/2){
                        if(t != lis[i]){
                            MOVE.isMove = true;
                            outer_wrap.insertBefore(div,lis[i]);
                        }

                    }else if(current.x > lis[i]['pos']['x'] && current.x < lis[i]['pos']['x'] + lis[i]['size']['width'] && current.y > lis[i]['pos']['y'] + lis[i]['size']['height']/2 && current.y < lis[i]['pos']['y'] + lis[i]['size']['height']){
                        if(t != lis[i]){
                            MOVE.isMove = true;
                            outer_wrap.insertBefore(div,lis[i].nextSibling);
                        }
                    }
                }
            }
//移除事件
            document.onmouseup = function(event){
                event = event || window.event;
                document.onmousemove = null;
                if(MOVE.isMove){
                    outer_wrap.replaceChild(t,div);
                    MOVE.isMove = false;
                }
                document.body.removeChild(el);
                el = null;
                document.body.style.cursor = 'normal';
                document.onmouseup = null;
            }
        }
    }
</script>
</body>
</html>
View Code

 

jQuery  拖拽交换位置(电脑端)

<!doctype html>
<html>
<head>
    <meta charset='utf-8' />
    <meta name="viewport"
          content="
        width = device-width ,
  height = device-height ,
        initial-scale = 1,
        minimum-scale = 1,
        maximum-scale = 1,
        user-scalable =no,

  "
    />
    <title></title>

    <style>
        * { padding:0;margin:0;list-style: none }
        html,body { height:100%; overflow:hidden; }
        ul { margin:50px auto;position:relative; width:1100px; height:500px;}
        ul li { float:left; width:25%; cursor:pointer; padding:10px; box-sizing:border-box; height:33%}
        ul img { height:100%;width:100%; box-shadow:0 3px 4px rgba(102,102,102,0.5) }
    </style>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>



<script>
    $(function(){


        var ps={L:[],R:[],T:[],B:[]};
        for(var i=11; i>=0; i--){
            var oLi = $('li').eq(i),
                    gLi = oLi.get(0);

            oLi.css({'left':gLi.offsetLeft+'px','top':gLi.offsetTop+'px','position':'absolute','margin':0});
            ps.L.push(gLi.offsetLeft);
            ps.T.push(gLi.offsetTop);
            ps.R.push(gLi.offsetLeft + gLi.offsetWidth);
            ps.B.push(gLi.offsetTop + gLi.offsetHeight);
        };
        ps.L = ps.L.reverse();
        ps.R = ps.R.reverse();
        ps.T = ps.T.reverse();
        ps.B = ps.B.reverse();  //储存位置


        //初始化
        var b = 0;

        $(document).on('mousedown','li',function(e){
            e.preventDefault();
            var _this = this;
            if(_this.setCapture){_this.setCapture()};
            var X = e.clientX - _this.offsetLeft,
                    Y = e.clientY - _this.offsetTop,
                    oList = $('li'),
                    attr = [];
            my_index = $( _this ).attr('index');     //初始保存一个原来的Index,回到原来的数组(位置)
            $(_this).css({'opacity':0.9,'zIndex':1});
            document.index = my_index;             //目的是为了脱离变量作用域

            $('li').each(function() {
                attr.push( $(this).attr('index') )
            });

            $(document).on('mousemove',function(e){
                var lt = e.clientX - X,
                        tp = e.clientY - Y,
                        screen_l = e.clientX - _this.parentNode.offsetLeft,
                        screen_t = e.clientY - _this.parentNode.offsetTop;
                $(_this).css({'left':lt+'px','top':tp+'px'});

                for(var i=0;i<12;i++){

                    var he_index = parseInt(oList.eq(i).attr('index'));
                    if(screen_l>ps.L[he_index]&&screen_l<ps.R[he_index]&&screen_t>ps.T[he_index]&&screen_t<ps.B[he_index]){
                        var i_index = parseInt($(_this).attr('index'));
                        if(he_index == i_index)continue;
                        document.index = he_index;              //当找到元素保存要抵达的位置的index
                        document.flag = false;
                        var test = function (num,j){
                            var he_Li = $('li[index='+j+']');
                            $(he_Li).stop();
                            he_Li.animate({
                                left:ps.L[j+num],
                                top:ps.T[j+num]
                            },'fast');
                            he_Li.attr('index',j+num);
                        };
                        //利用属性选择器找到对应index(也就是找到数组相应位置)的元素;并且变换属性index到相应的数组索引;

                        if(i_index>he_index){
                            for(var j=i_index-1; j>=he_index; j--){
                                test(1,j);
                            }
                        }else{
                            for(var j=i_index+1; j<he_index+1; j++){
                                test(-1,j);
                            }
                        };
                        $(_this).attr('index',he_index);  //变换_this的index
                        document.flag = true;

                    }else{
                        if(document.flag){
                            var parent = _this.parentNode,
                                    parent_X = e.clientX - parent.offsetLeft,
                                    parent_Y = e.clientY - parent.offsetTop;
                            if( parent_X<0||parent_X>parent.offsetWidth||parent_Y<0||parent_Y>parent.offsetHeight ){
                                oList.not(_this).each(function(index, element) {
                                    var a = $(element).index();
                                    $(element).animate({
                                        left:ps.L[attr[a]],
                                        top:ps.T[attr[a]]
                                    },'fast').attr('index',attr[a])
                                });
                                document.index = my_index;
                                $(_this).attr('index',my_index);
                                document.flag = false;
                                //当移出父节点还原
                            }

                        }
                    };

                };
            });
            $(document).on('mouseup',function(){
                if(_this.releaseCapture){
                    _this.releaseCapture();
                };
                $(this).off('mousemove');
                $(this).off('mouseup');

                $(_this).animate({
                    left:ps.L[document.index],
                    top:ps.T[document.index]
                },'fast',function(){
                    $(_this).css({'opacity':1,'zIndex':0})
                });
                delete document.index;
                delete document.flag;

            });
        });


    })
</script>


<ul>
    <li index="0"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="1"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="2"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="3"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="4"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="5"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="6"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="7"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="8"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="9"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="10"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>
    <li index="11"><img src="http://www.baidu.com/img/bd_logo1.png" title="百度" /></li>

</ul>
</body>
</html>
View Code

 

 


 

拖放移动位置如:(移动端拖拽的实现效果)

http://blog.csdn.net/xyphf/article/details/51988947

 

移动端 javascript 实现长按拖动

https://segmentfault.com/q/1010000008667545

 

posted @ 2017-03-09 18:24  James2019  阅读(928)  评论(0编辑  收藏  举报