Wscats / CV

:see_no_evil:Front End Engineer Curriculum Vitae - 面试宝典和简历生成器
http://wscats.github.io/CV/omi/build/index.html
1.04k stars 203 forks source link

day6 #20

Closed Wscats closed 7 years ago

Wscats commented 7 years ago

数组forEach()

// ES新增的数组方法
var arr = ['html5', 'css3', 'ecmascript5', 'jquery', 'angular'];

/*for(var i=0;i<arr.length;i++){
    var new = ''
    document.write('<p>' + arr[i] + '</p>');
}*/

// 用于遍历数组的forEach()
// forEach的缺点:不能使用break/continue
arr.forEach(function(item, idx, arr) {
    console.log(item, idx, arr);
    // item就是for循环中的arr[i]
    document.write('<p>' + item + '</p>');
});

数组map()

// map()
var arr = [10, 20, 30, 5, 100];

var newArr = arr.map(function(item) {
    console.log(item);

    // 一定要有一个返回值
    // 返回一个增加20%的数
    // 得到数组元素取决于下面的return值

    // return item + item*0.2
    return item * item;
});
console.log(newArr, arr)

数组every()

// 判断arr中的数是否都大于10
var res = arr.every(function(item) {
    return item > 10;
});
console.log(res);

数组some()

// 只要数组中有一项符合return后的条件(返回true)
var res = arr.some(function(item) {
    return item > 20;
});
console.log(res);

前端搜索

<input id="input" onkeyup="search()" />
<ul id="ul"></ul>
<script>
    var arr = ['html5', 'css3', 'ecmascript5', 'jquery', 'css3', 'angular'];

    function search() {
        var input = document.getElementById("input").value;
        var newArr = [];
        arr.forEach(function(item) {
            if(item.indexOf(input)) {} else {
                newArr.push(item)
            }
        });
        console.log(newArr, arr)
        var str = newArr.map(function(item) {
            return "<p>" + item + "</p>";
        }).join("");
        console.log(str)
        document.getElementById("ul").innerHTML = str
    }
</script>

严格模式

作用域

'use strict';
var arr = [10, 20, 30];
var num = 100;
function sum() {
    // 'use strict';
    // 不适用var声明的变量在正常模式下会称为全局变量
    // 在严格模式下会报错
    x = 100;
    console.log(x);
}
sum();

删除全局变量

'use strict';
// delete
var obj = {
    name: '1612',
    add: '广州'
}
obj.add = '广州天河';
// 删除add属性
delete obj.add;
//不能删除obj全局变量
delete obj;
console.log(obj)
// 全局变量是不可删除的属性
window.num = 100;
delete num; //删除失败,因为num为全局变量
console.log(num);

arguments

function test() {
    'use strict';
    console.log(arguments);
    // 交换arguments中的参数位置
    var temp = arguments[0];
    arguments[0] = arguments[1];
    arguments[1] = temp;
    console.log(arguments);
}
test(1, 2)

arguments.callee

var num = 100;
function factorial(num) {
    // 'use strict'
    if(num === 1) {
        return 1;
    }
    return num * arguments.callee(num - 1);
}
console.log(factorial(5));

不允许把函数声明写在条件判断/循环语句中

'use strict'
for(var i = 0; i < 100; i++) {
    function test(idx) {
        console.log(idx);
    }
    test(i);
}

字符串创建

//方式一:字面量(推荐)
var str = '城市套路深,我想回农村';
//方式二:构造函数:
var str2 = new String('城市套路深,我想回农村');
console.log(typeof str);
console.log(typeof str2);
//字符长度
console.log(str.length);

正则表达式

var str = 'Good good study, day day up';
// 字面量
var reg = /good/gi; //good=>hao
// 构造函数
var reg = new RegExp('good', 'gi');
// 参数
// i,g
console.log(str.replace(reg, 'hao'));

提取url的参数

/*
            取出name, age和gender的值
            1)先获取?后的字符
            2)用&分隔字符串为数组
            3)遍历数组,提取name,age,gender
         */
var url = 'https://www.baidu.com/s?name=wangmouqiang&age=20&gender=male'
console.log(url.substring(2, 5));
console.log(url.substr(-10, 5));
// var name = url.substr(url.indexOf('name=')+5,6);
// console.log(name)
// 1)先获取?后的字符
var idx = url.indexOf('?');
var attr = url.substring(idx + 1);
attr = attr.split('&');
console.log(attr)
attr.forEach(function(item) {
    var arr = item.split('=');
    console.log(arr[0], arr[1]);
});

加密解密

window.onload = function() {
    var msg = document.getElementById('msg');
    var btn = document.getElementById('btn');
    var output = document.getElementById('output');
    var btn2 = document.getElementById('btn2');
    // 绑定点击事件
    btn.onclick = function() {
        var _msg = msg.value;
        var arr = [];
        for(var i = 0; i < _msg.length; i++) {
            arr.push(_msg.charCodeAt(i));
        }
        output.innerHTML = arr.join();
    }
    // 加密
    btn2.onclick = function() {
        var _msg = output.innerHTML;
        // 转回数组
        var arr = _msg.split(',');
        var str = '';
        arr.forEach(function(num) {
            str += String.fromCharCode(num);
        });
        output.innerHTML = str;
    }
}
Wscats commented 7 years ago

Date

var date = new Date();
console.log(date);
console.log(date.toDateString());
//以特定的格式显示星期几、 月、 日和年
console.log(date.toTimeString());
//以特定的格式显示时、 分、 秒和时区
console.log(date.toLocaleDateString());
//以特定地区格式显示年、 月、 日
console.log(date.toLocaleTimeString());
//以特定地区格式显示时、 分、 秒
console.log(date.toUTCString());

var date2 = new Date("2015/08/22");
console.log(date2.getFullYear());

倒计时效果

var countDown = document.getElementById('countDown');
var btnBuy = document.getElementById('btnBuy');
// var endDate = '2017/2/23';
// 如何创建指定时间对象
var endDate = new Date('2017/8/29 07:43:10');
myCountDown();
var timer = setInterval(myCountDown, 1000);

function myCountDown() {
    var now = new Date();
    // 计算时间差
    // 把时间转换成毫秒数再相减
    // 372s = > 72分12s
    var offset = Math.floor((endDate.getTime() - now.getTime()) / 1000);
    // 格式:1天1小时20分30秒
    // 计算剩余秒数
    var secLeft = offset % 60;
    // 计算剩余的分钟数
    var minLeft = parseInt(offset / 60) % 60;
    var hourLeft = parseInt(offset / 60 / 60) % 24
    var dayLeft = parseInt(offset / 60 / 60 / 24)
    // 写入页面
    countDown.innerHTML = dayLeft + '天' + hourLeft + '时' + minLeft + '分' + secLeft + '秒';
    if(offset <= 0) {
        clearInterval(timer);

        // 改变为可购买图片路径
        btnBuy.src = 'img/btn_buy.jpg';

        // 隐藏倒计时
        countDown.style.display = 'none';
    }
}

随机颜色

var str = '0123456789abcdef';
function randomColor() {
    var res = '#';
    for(var i = 0; i < 6; i++) {
        // 先获取随机索引值
        var idx = Math.floor(Math.random() * str.length);
        res += str[idx];
    }
    return res;
}
// document.getElementById('myBody').style.backgroundColor = randomColor();
// 获取body元素的方式
document.body.style.backgroundColor = randomColor();

轮播图

var girl = document.getElementById('girl');
var btnStop = document.getElementById('btnStop');
//每3s切换一张图片
var idx = 1;
var timer = setInterval(carousel, 1000);
// 轮播函数
function carousel() {
    idx++;
    girl.src = 'img/g' + idx + '.jpg';
    if(idx >= 5) {
        // clearInterval(timer);
        idx = 0;
    }
}
// 点击暂停
btnStop.onclick = function() {
    if(timer) {
        clearInterval(timer);
        timer = undefined;
        btnStop.innerHTML = '轮播';
    } else {
        timer = setInterval(carousel, 1000);
        btnStop.innerHTML = '暂停';
    }

}

复杂的轮播图

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>

    <body>
        <style>
            #container {
                position: relative;
                height: 320px;
                width: 320px;
                overflow: hidden;
            }

            #list {
                position: absolute;
                left: 0;
                width: 1600px;
                height: 320px;
            }

            img {
                float: left;
            }
        </style>
        <div id="container">
            <div id="list">
                <img src="../img/g1.jpg" alt="1" />
                <img src="../img/g2.jpg" alt="2" />
                <img src="../img/g3.jpg" alt="3" />
                <img src="../img/g4.jpg" alt="4" />
                <img src="../img/g5.jpg" alt="5" />
            </div>
        </div>
        <button id="start">开始</button>
        <button id="stop">停止</button>
        <button id="pre">前一张</button>
        <button id="nx">后一张</button>
        <script>
            var offset = 0;
            function move() {
                offset -= 320
                document.getElementById("list").style.left = (offset + "px");
                if(offset == -1600) {
                    offset = 0;
                    document.getElementById("list").style.left = "0px";
                }
            }
            document.getElementById("pre").onclick = function() {
                if(offset == 0) {
                    offset = -1600;
                }
                offset += 320;
                document.getElementById("list").style.left = (offset + "px");
            }
            document.getElementById("nx").onclick = function() {
                if(offset == -1280) {
                    offset = 320;
                }
                offset -= 320;
                document.getElementById("list").style.left = (offset + "px");
            }
            var animation = setInterval(move, 1000);
            document.getElementById("start").onclick = function() {
                clearInterval(animation)
                animation = setInterval(move, 1000);
            }
            document.getElementById("stop").onclick = function() {
                clearInterval(animation)
            }
        </script>
    </body>

</html>
Wscats commented 7 years ago

对象的创建

dog.smell = function() {
    console.log('闻一闻')
}
dog.lick = function() {
    console.log('舔一舔')
}
dog.bite = function() {
    console.log('咬一咬')
}

dog.smell();
dog.lick();
dog.bite();

// 对象的属性
// 对象有什么
var person = {
    name: 'xx',
    age: 18,
    gender: 'man'
}

// 对象的方法
// 对像能做什么
person.eat = function() {

}

// 封装:工厂函数
function createDog(opt) {
    // 1.创建一个对象
    var dog = {
        // ....
    }

    // 2.描述一个对象
    // 描述这个对象有什么
    // 描述这个对象能做什么
    dog.smell = function() {
        console.log('闻一闻')
    }
    dog.lick = function() {
        console.log('舔一舔')
    }
    dog.bite = function() {
        console.log('咬一咬')
    }

    return dog;
}
var dog1 = createDog({
    color: '#ff0',
    name: ''
});
Wscats commented 7 years ago

描述一个对象

// 描述一个人
// 1.人有什么特征(属性)
// 2.人能做什么(方法)
var person = {
    // 属性
    name: '三胖',
    gender: '男',
    age: 18,

    // 方法
    coding: function() {

    },
    play: function() {

    },
    eat: function() {}
}

// QQ聊天窗口
var qqchat = {
    title: '老姚',
    width: 480,
    height: 300,
    toolbar: [{}, {}],
    ad: [],
    msg: []
    textarea: obj,
    btnClose: '#btnClose',
    btnSend: '#btnSend'

    // 方法
    send: function() {},
    close: function() {},
    hongbao: function() {}
}

// 描述放大镜效果
var zoom = {
    smallImg: 'img/small.jpg',
    bigImg: 'img/big.jpg',
    width: 480,
    height: 300,
    bigContainer: '#bigContainer',

    // 方法
    // 初始化方法
    // 生成节点,绑定事件
    init: function() {},

    // 显示大图和放大镜
    show: function() {},

    // 隐藏
    hide: function() {

    }
}
Wscats commented 7 years ago

构造函数

var obj = new Object();
obj.name = '哈巴';

// 自定义构造函数
function Dog() {
    this.name = '哈巴';
    this.color = '白色';

    this.jiao = function() {
        console.log(`我的名字叫${this.name}`);
    }
}

// 调用自定构造函数
// 创建对象新方式
var habadog = new Dog();
console.log(habadog);
habadog.jiao();

// 普通函数执行方式
// Dog(); => undefined
// 构造函数的调用方式
// new Dog(); => 对象

// 构造函数的约定:首字母大写
// Oject,String,Number,Boolean,Date,RegExp,Array...

构造函数经历的步骤

// 自定义构造函数
function Dog() {
    /*
        以下4步在执行new Dog()时完成:
        1. var obj = new Object()
        2. 改变this的指向
        3. 执行内部代码,给对象写入属性/方法
        4. 返回一个对象
     */
    this.name = '哈巴';
    this.color = '白色';

    this.jiao = function() {
        console.log(`我的名字叫${this.name}`);
    }
}

// 调用自定构造函数
// 得到一个对象,这个对象称之为:实例对象
var habadog = new Dog();

原型对象

// 构造函数
function SuperStar(name, age, type) {
    // 描述属性
    this.name = name;
    this.age = age;
    this.type = type;

    /*// 描述方法
    this.sing = function(){
        console.log(`我叫${this.name},我会唱歌`);
    }
    this.liaomei = function(){
        console.log(`我叫${this.name},我会撩妹`);
    }
    this.paoba = function(){
        console.log(`我叫${this.name},我会泡吧`);
    }*/
}

// 原型对象
// 利用原型对象优化代码
SuperStar.prototype.sing = function() {
    console.log(`我叫${this.name},我会唱歌`);
}
SuperStar.prototype.liaomei = function() {
    console.log(`我叫${this.name},我会撩妹`);
}
SuperStar.prototype.paoba = function() {
    console.log(`我叫${this.name},我会泡吧`);
}

console.log(SuperStar.prototype)

// 示例
var huge = new SuperStar('胡歌', 26, '影视明星');
var wuyifan = new SuperStar('吴亦凡', 22, '小鲜肉');
var marong = new SuperStar('马蓉', 28, '经纪人老婆');

console.log(huge, wuyifan, marong)
wuyifan.sing();

// 通过示例得到原型对象
// 通过wuyifan得到原型对象
// 私用属性:__proto__
// ES5的方法:Object.getPrototypeOf(实例)
console.log(wuyifan.__proto__);
console.log(Object.getPrototypeOf(wuyifan));

/*var obj = {}
obj.name = 'xxx';
obj.say = function(){
    alert(6666)
}
obj.call()*/
Wscats commented 7 years ago

转码解码

// 转码解码
// decodeURI()/decodeURIComponent()
var attr = decodeURIComponent(location.search);
console.log(location.search);
console.log(attr);
window.onload = function() {
    var btnRefresh = document.getElementById('btnRefresh');

    btnRefresh.onclick = function() {
        location.reload(true);
    }
}

window.onload

onclick/onload

console.log(document.body)
window.onload = function() {
    console.log(document.body)
}
console.log(document.body)

吸顶和置顶菜单

注意window.scrollY不能赋值

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>10吸顶菜单</title>
        <style>
            body {
                margin: 0;
                padding-bottom: 1000px;
            }

            header {
                height: 100px;
                background-color: #ffc;
            }

            #menu {
                width: 100%;
                height: 50px;
                background-color: #f00;
            }

            ul {
                line-height: 2;
            }
        </style>
        <script>
            window.onload = function() {
                var menu = document.getElementById('menu');
                // 滚动事件
                window.onscroll = function() {
                    console.log(window.scrollY)
                    // 获取滚动条滚动过的距离
                    // window.scrollY
                    if(window.scrollY >= 100) {
                        menu.style.position = 'fixed';
                        menu.style.left = 0;
                        menu.style.top = 0;
                    } else {
                        menu.style.position = 'static';
                    }
                }
                menu.onclick = function() {
                    var scrollTop = window.scrollY;
                    var timer = setInterval(function() {
                        scrollTop -= 10;
                        if(scrollTop <= 0) {
                            scrollTop = 0;
                            clearInterval(timer)
                        }
                        window.scrollTo(0, scrollTop)
                    }, 50)
                }

            }
        </script>
    </head>
    <body>
        <header>
            欢迎光临
        </header>
        <div id="menu">
            吸顶菜单
        </div>
        <ul>
            <li>
                <a href="#">分类1</a>
            </li>
            <li>
                <a href="#">分类1</a>
            </li>
            <li>
                <a href="#">分类1</a>
            </li>
            <li>
                <a href="#">分类1</a>
            </li>
            <li>
                <a href="#">分类1</a>
            </li>
            <li>
                <a href="#">分类1</a>
            </li>
            <li>
                <a href="#">分类1</a>
            </li>
            <li>
                <a href="#">分类1</a>
            </li>
        </ul>
    </body>

</html>
Wscats commented 7 years ago

parentNode、previousSibling、nextSibling和previousElementSibling、nextElementSibling

表格增删查改

var table = document.querySelector("#table");
var tbody = table.querySelector("tbody");
var tr = document.querySelectorAll("#table tr");
console.log(tr)

function create() {
    var tr = document.createElement("tr");
    tr.innerHTML = "<th>1</th><th>2</th><th><button>Ok</button></th>";
    tr.querySelector("button").onclick = function() {
        tbody.removeChild(this.parentNode.parentNode)
    }
    tbody.appendChild(tr);
}
for(var i = 0; i < tr.length; i++) {
    var button = tr[i].lastElementChild.firstChild;
    button.onclick = function() {
        console.log("ok")
        console.log(button.parentNode.parentNode)
        tbody.removeChild(button.parentNode.parentNode)
    }
}
Wscats commented 7 years ago

拖拽效果.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>15拖拽效果</title>
    <style>
        .pop{position: absolute;width:480px;border:1px solid #ddd;}
        .pop header{padding-left:10px;height:40px;line-height:40px;border-bottom:1px solid #ddd;}
        .pop .content{padding:15px;min-height:100px;}
        .pop .btn-close{position:absolute;top:0;right:0;padding:10px;}
        .pop .btn-close:hover{background-color: #f00;color:#fff;}
    </style>
    <script>
        window.onload = function(){
            var pop = document.getElementsByClassName('pop')[0];
            var btnClose = pop.getElementsByClassName('btn-close')[0];
            var header = pop.getElementsByClassName('header')[0];

            // 给弹窗绑定mousedown事件
            header.onmousedown = function(evt){
                // 保存按下时光标距离header的距离
                var ox = evt.offsetX;
                var oy = evt.offsetY;

                // 在mousedown事件中给document绑定mousemove事件
                document.onmousemove = function(e){
                    pop.style.left = e.clientX - ox + 'px';
                    pop.style.top = e.clientY - oy + 'px';

                    e.preventDefault();
                }
            }

            // 鼠标弹起后清除document的mousemove事件
            header.onmouseup = function(){
                document.onmousemove = null;
            }

            // 关闭
            btnClose.onmousedown = function(e){
                pop.style.display = 'none';

                // 阻止事件冒泡只能阻止同类事件
                e.stopPropagation();
            }

        }
    </script>
</head>
<body>
    <div class="pop">
        <header class="header">
            弹窗标题
        </header>
        <div class="content"></div>
        <span class="btn-close">&times;</span>
    </div>
</body>
</html>

事件监听

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>16事件监听</title>
    <script>
        window.onload = function(){
            document.addEventListener("click",function(){
                console.log("点击了DOM")
            })
            /*
                事件绑定的第二中方式:
                事件监听addEventListener()
             */
            var btn =document.getElementById('btn');
            var btn2 =document.getElementById('btn2');

            // 这种事件绑定方法同名事件会被覆盖
            btn.onclick = function(){
                console.log('click');
            }

            btn.onclick = function(){
                console.log('第二次click');
            }

            btn.addEventListener('click',function(){
                console.log('第三次click');
            },false);

            btn.onclick = function(){
                console.log('第四次click');
            }

            // 清除事件
            btn.onclick = null;

            // 事件监听
            // addEventListener()
            btn2.addEventListener('click',function(e){
                console.log('第1次点击')
            },false);
            btn2.addEventListener('click',function(e){
                e.stopPropagation();
                console.log('第2次点击')
            },false);

            // 推荐的事件监听方式
            // 用具名函数
            function handler(){
                console.log('第3次点击')
            }
            btn2.addEventListener('click',handler,false);

            // 清除事件监听
            // 参数一定要跟绑定时一样
            btn2.removeEventListener('click',handler);

            // ie8-的事件监听方式
            // attachEvent('onclick',)
            // 没有第三个参数
            // btn2.attachEvent('onclick',handler);
            // 
            // IE8-清除事件监听
            // btn2.detachEvent('onclick',handler);
        }
    </script>
</head>
<body>
    <button id="btn">按钮</button>
    <button id="btn2">按钮2</button>
</body>
</html>

事件捕捉和冒泡

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>17事件捕获</title>
    <style>
        #box{border:1px solid #ddd;padding:10px;}
    </style>
    <script>
        window.onload = function(){
            var box = document.getElementById('box');
            box.addEventListener('click',function(e){
                console.log('div#box');
                //e.stopPropagation();
            });
            document.body.addEventListener('click',function(e){
                console.log('body');
                // 阻止事件传播(捕获,冒泡)
                e.stopPropagation();
            },true);
            /*document.addEventListener('click',function(e){
                console.log('body2');
                // 阻止事件传播(捕获,冒泡)
                e.stopPropagation();
            },true);*/

            // 事件捕获
            document.addEventListener('click',function(){
                console.log('document');
            },true);
            window.addEventListener('click',function(){
                console.log('window');
            })
        }
    </script>
</head>
<body>
    <div id="box">
        事件捕获效果
    </div>
</body>
</html>

自定义菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>14自定义菜单</title>
    <style>
        ul{list-style: none;padding:0;margin:0;}
        .contextMenu{display:none;position:absolute;padding:1px;width:200px;border:1px solid #ddd;line-height:2;}
        .contextMenu li{position:relative;padding-left:10px;border-bottom:1px dotted #ddd;}
        .contextMenu li:last-child{border-bottom:none;}
        .contextMenu li:hover{background-color: #f5f5f5;}
        .contextMenu li span{position: absolute;right:10px;top:0;color:#999;}
    </style>
    <script>
        window.onload = function(){
            var contextMenu = document.getElementsByClassName('contextMenu')[0];
            // 给document绑定contextmenu事件
            document.oncontextmenu = function(e){
                e = e || window.event;
                contextMenu.style.left = e.clientX + 'px';
                contextMenu.style.top = e.clientY + 'px';
                contextMenu.style.display = 'block';
                // 阻止浏览器默认右键菜单
                if(e.preventDefault){
                    e.preventDefault();
                }else{
                    e.returnValue = false;
                }
            }
            // 点击空白处隐藏右键菜单 
            document.onclick = function(){
                contextMenu.style.display = 'none';
            }
            // ESC关闭
            document.onkeyup = function(e){
                e = e || window.event;
                var keyCode = e.keyCode || e.which;
                if(keyCode === 27){
                    contextMenu.style.display = 'none';
                }
            }
            // contextMenu.onclick = function(e){
            //  e.stopPropagation();
            // }
        }
    </script>
</head>
<body>
    <div class="contextMenu">
        <ul>
            <li>复制<span>Ctrl+C</span></li>
            <li>粘贴<span>Ctrl+V</span></li>
            <li>剪切<span>Ctrl+X</span></li>
            <li>删除<span>Del</span></li>
            <li>保存<span>Ctrl+S</span></li>
        </ul>
    </div>
</body>
</html>
Wscats commented 7 years ago

拖拽轨迹回放

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>18拖拽轨迹回放</title>
    <style>
        img{position: absolute;}
    </style>
    <script>
        window.onload = function(){
            /*
                拖拽轨迹回放
                1)鼠标按下且移动时,记录光标移动过的位置到数组arr_pos
                2)鼠标弹开后,依次把图片的top,left值改成arr_pos中的坐标
             */
            var monkey = document.images[0];
            // 用于记录鼠标移动过的位置
            var arr_pos = [];
            // 给document绑定mousedown事件
            document.onmousedown = function(e){
                // 先记录按下时的坐标
                arr_pos.push({x:e.clientX,y:e.clientY});

                // 按下并移动时,记录移动过的位置坐标
                document.onmousemove = function(evt){
                    arr_pos.push({x:evt.clientX,y:evt.clientY});
                }
            }
            // 鼠标弹起
            // 让图片沿着记录的坐标移动
            document.onmouseup = function(){
                var idx = 0;
                // 先把图片移动到记录坐标的初始位置
                monkey.style.left = arr_pos[idx].x + 'px';
                monkey.style.top = arr_pos[idx].y + 'px';
                // 启用攻击状态
                monkey.src = 'img/2.gif';
                var timer = setInterval(function(){
                    idx++;
                    monkey.style.left = arr_pos[idx].x + 'px';
                    monkey.style.top = arr_pos[idx].y + 'px';
                    // 当图片移动到最后的位置时,停止定时器
                    if(idx>=arr_pos.length-1){
                        clearInterval(timer);
                        // 清空数组
                        arr_pos = [];
                        // 移动完成后回复初始状态
                        monkey.src = 'img/1.gif';
                    }
                },30);
                // 鼠标弹起后清除mousemove事件
                document.onmousemove = null;
            }
        }
    </script>
</head>
<body>
    <img src="img/1.gif">
</body>
</html>