十、自定义指令练习

2018-02-26  本文已影响0人  飞奔的小白

练习

拖动页面中的元素
onmouseover onmouseout
onmousedown onmousemove onmouseup
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>指令</title>
<script type="text/javascript" src="js/vue.min.js"></script>
</head>
<style type="text/css">
#itany{
    width:300px;
    height:300px;
    position:absolute;
    background:pink;
}
#itany .one{
    background-color: red;
    top: 0;
    left:0;
    width:100px;
    height:100px;
    position: absolute;
}
#itany .two{
    background-color: blue;
    top:0;
    right:0;
    position: absolute;
    width:100px;
    height:100px;
}
</style>
<body>
<div id="itany">
    <div class="one" v-drag>itany</div>
    <div class="two" v-drag>shehui</div>
</div>
</body>
<script type="text/javascript">
Vue.directive('drag',function(el){
    el.onmousedown=function(e){
        // 获取鼠标点击处分别与div左边和上边的距离:鼠标位置-div位置;
        var disX = e.clientX-el.offsetLeft;
        var disY = e.clientY-el.offsetTop;
        console.log(disX,disY);
        // 包含在ononmousedown里面,表示点击后才移动,为防止鼠标移除div,使用document.onmousemove
        document.onmousemove= function (e) {
             var l = e.clientX - disX;
             var t = e.clientY - disY;
             el.style.left = l +'px';
             el.style.top = t + 'px'; 
        }
        document.onmouseup = function(e){
            document.onmousemove = null;
            document.onmouseup = null;
        }
    }
})
var vm = new Vue({
    el:'#itany',
    data:{
        msg:'welcome to itany',
        username:'alice'
    },
    methods:{
        change(){
            this.msg="欢迎来到北京";
        }
    },
})
</script>
</html> 
上一篇下一篇

猜你喜欢

热点阅读