码迷,mamicode.com
首页 > 移动开发 > 详细

js里div随着鼠标一起移动

时间:2017-07-05 13:20:49      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:随机数   创建   position   else   ams   速度   屏幕   ram   rand   

<script>
    function move(keynum) {
        //获取屏幕宽度
        var w=screen.availWidth;
        //获取屏幕高度
        var h=screen.availHeight
        var d = document.getElementById("dv");
        //创建随机数,也就是我们的移动速度
        var speed=Math.floor(Math.random()*100);

        switch (keynum) {
            case 65://a--向左移动
                if(d.offsetLeft<5){
                    d.style.left=w/2+"px";
                }else{
                    d.style.left = d.offsetLeft - speed + "px";             
                }
            break;
            case 68://d---右移动
                if(d.offsetLeft>screen.w-speed){
                    d.style.left=w/2+"px";
                }else{
                    d.style.left = d.offsetLeft + speed + "px";
                }
            break;
            case 87://w---向上移动
                if(d.offsetTop<speed){
                    d.style.top=h/2+"px";
                }else{
                    d.style.top = d.offsetTop - speed + "px";
                }
            break;
            case 83://s---向下移动
                if(d.offsetTop>h-speed){
                    d.style.top=h/2+"px";
                }else{
                    d.style.top = d.offsetTop + speed + "px";
                }
            break;
        }
    }
    function keyChange(e){
        var keynum;
        if (window.event) // IE
        {
            keynum = e.keyCode
        } else if (e.which) // Netscape/Firefox/Opera
        {
            keynum = e.which
        }
        move(keynum);
    }
    //随着鼠标一起动
    /* document.onmousemove=function showxy(e) {
        if(!e){
            e = window.event;           
        }
        var d = document.getElementById("dv");
        d.style.left=e.clientX+"px";
        d.style.top=e.clientY+"px";
        //alert(e.clientX+","+e.clientY);
    } */
    //点击鼠标移动
    document.onmousedown=function showxy(e) {

        var d = document.getElementById("dv");
        d.style.left=e.clientX+"px";
        d.style.top=e.clientY+"px";
    }
</script>

<body onkeydown="keyChange(event)">
    <div style="position: absolute; left: 100px; top: 100px;" id="dv">
        <img src="ball.png" width="50px" height="50px" />
    </div>
</body>

js里div随着鼠标一起移动

标签:随机数   创建   position   else   ams   速度   屏幕   ram   rand   

原文地址:http://www.cnblogs.com/Marlboro-pm/p/7120316.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!