红叶都枫了 @163

js实现一个拖拽效果(本例vue中),边界限定,获取鼠标坐标,div坐标

有事没事搞个图:

 

 demo:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=1.0, user-scalable=0">
<title>九宫格</title>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<style>
html,body{
      margin: 0;
      padding: 0;
      height: 98%;
      width: 100%;
      padding-top: 2%;
    }
    #app{
        width: 100%;
        position: relative;
        left: 0;
    }
    #box{
        position: fixed;
        bottom: 0;
        margin: 0 auto;
        width:100px;
        height:100px;
        background-color: gray;
    }
    #box>div{
        color: skyblue;
    }
</style>
<script type="text/javascript">
    window.onload=function(){
        var app = new Vue({
            el: '#app',
            data: {
                X:0,
                Y:0
            },
            created(){

            },
            methods:{
                touchmove(event){
                    this.X = event.targetTouches[0].clientX
                    this.Y = event.targetTouches[0].clientY
                    let screenWid = $(window).width()
                    let screenHei = $(window).height()
                    let midLeft =  event.targetTouches[0].clientX-($('#box').width()/2)
                    let midRight = $(window).width()-(event.targetTouches[0].clientX+($('#box').width()/2))
                    let midBottom = $(window).height()-(event.targetTouches[0].clientY+($('#box').width()/2))
                    let midTop = event.targetTouches[0].clientY-($('#box').height()/2)
                    if(midLeft<0) midLeft = 0
                    if(midTop<0) midTop = 0
                    if(midRight<0) return
                    if(midBottom<0) return
                    $('#box').css({left:midLeft,top:midTop})
                }
            }
        })
    }
</script>
<!-- 引入vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <div id="box" @touchmove='touchmove'>
            <div>鼠标x:{{X}}</div>
            <div>鼠标y:{{Y}}</div>
        </div>
    </div>
</body>
</html>

 

posted @ 2020-03-20 15:42  红叶都枫了163  阅读(1400)  评论(0编辑  收藏  举报