美文网首页
前端-02-js

前端-02-js

作者: 西海岸虎皮猫大人 | 来源:发表于2020-09-06 21:18 被阅读0次
1.语法基础
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<script>
    // 1.一般script写在body里

    // 2.上线之前会对代码进行压缩,去掉空格换行\变量名替换

    // 3.进制
/*     // 8进制
    console.log(0o123);
    // 16进制
    console.log(0xf); */

   // 4.undefined 声明提升
/*     console.log(a);
    var a = 10; */

    // 5.全局变量
/*     a =  100; */

    // 6.连续赋值
/*     var a = 10, b = 20, c = 30; */

    // 7.数据类型 
    // number string undefined null boolean
/*     console.log(typeof a); */

    // 8.科学计数法
/*     var f = 1e5; */

    // 9.Infinity 无穷大 number类型 -Infinity
/*     var c = 1/0; */

    // 10.NaN not a number
/*     var d = 0/0; */

    // 11.类型转换
    // 用户输入,默认值18
/*     var age = prompt('请输入年龄', 18)
    // string类型
    console.log(age, typeof age)
    // 转换为整数
    var age1 = parseInt(age);
    console.log(typeof age1);
    // 会截取数字部分
    console.log(parseInt('18haha'));
    // 整形转浮点型
    var b = parseFloat(age1)
    // 非数字开头转换时转为NaN
    var c = '18';
    // 转为数字,隐式
    var d = c - 0;
    // 数字转字符串
    var e = 10;
    var f = e + ''; */

    // 12.数学运算
/*    // 取余
    var a = 2%3;
    // 乘方
    var b = Math.pow(3, 5);
    // 根号
    var c = Math.sqrt(9); 
    // number 布尔值 null会进行隐式转换
    console.log(3 * '5');
    // true转为1 false转为0 null转为0
    console.log(3 * true);
    // 不纯字符串无法进行隐式转换,结果为NaN*/


    // 14.逻辑运算符
/*     // 全等 ?
    console.log(1===1);
    // 字符串顺序比较
    console.log('a' < 'b');
    console.log('abc' < 'adb');
    // 非数字转为数字
    console.log(1 > '0');
    console.log(1 == true);
    // 全等会判断类型,false
    console.log(1 === true);
    // false
    console.log(null == 0);
    // false NaN不能判断相等和全等
    console.log(NaN == NaN);
    // false
    console.log(NaN == NaN);
    // false true > 1
    console.log(3 > 2 > 1);

    // 逻辑运算短路
    var a = parseInt(prompt('请输入年龄', 18));
    a >= 18 && alert('可以考驾照');
    a < 18 && alert('不可以考驾照');

    // 负性 false null 0 NaN "" undefined */

    // 15.分支
    // 利用break实现多分支的相同逻辑
/*     var xingzuo = '巨蟹座';
    switch(xingzuo) {
        case '双鱼座':
            console.log('多愁善感');
            break;
        case '巨蟹座':
            console.log('恋家');
            break;
        default:
            console.log('未收录');
            break;
    } */

    // 16.循环
    for(var i=0; i<10; i++) {
        console.log(i);    
    }
    var i=1;    
    while(i<=10) {
        console.log(i);
        i++;
    }
</script>
</body>
</html>
2.函数
<script>
    // 1.函数基础
    // 函数定义
/*     function sum(a, b) {
        // 内置参数对象
        console.log(arguments[0], arguments[1]);
        // 返回值
        return a + b;
    }

    // 函数重载
    function sum(a, b, c) {
        console.log(a + b + c);
    }

    // 形参可以省略,直接操作arguments对象
    function sum() {
        if(arguments.length == 0) {
            console.log('没有参数');
        }
        var sum = 0;
        for(var i=0; i<arguments.length; i++) {
            sum += arguments[i];
        }
        console.log(sum);
    }

    // 递归,斐波那契数列
    function fibanacci(n) {
        if(n == 1 || n ==2) {
            return 1;
        } else {
            return fibanacci(n-1) + fibanacci(n -2);
        }
    }

    var sum = sum(10, 20);
    console.log(sum);
    sum(1, 2, 3, 4, 5, 6); */


    // 2.作用域

/*     // 函数内部可以调用函数外定义的变量
    var a = 10;
    function fun() {
        console.log(a);
    } */

    // 3.闭包
    // 函数内部的函数和局部变量暴露到外部
    // 内部作用域和外部的桥梁
/*     function outer() {
        var a = 10;

        function inner() {
            a++;
            console.log(a);
        }
        // 函数作为返回值,注意没有()
        return inner;
    }
    // 使用变量接收函数
    var inn = outer();
    inn();
    // 12
    inn(); */

    // 4.数组
/*     var arr = [1, 2, 3, 4, 5];
    console.log(arr);
    // 数组是对象类型,函数是function类型
    console.log(typeof arr);
    // 判断是否是函数
    console.log(Array.isArray(a));
    // 长度
    console.log(arr.length);
    // 数组遍历
    for(var i=0; i<arr.length-1; i++) {
        console.log(arr[1]);
    }
    // 改变数组长度
    arr.length = 2;
    // 通过下标修改数组长度
    arr[20] = 10;
    console.log(arr.length)
    // 数组元素可以是不同类型,包括函数
    var brr = ['1', 2, true, undefined, null, NaN, function fun() {console.log(1)}]; */

    // 5.数组常用方法
/*     var a = ['东', '西', '南', '北', '中'];
    // 添加到尾部
    var b = a.push('八万');
    // 返回数组新的长度
    console.log(b);
    // 获取尾部元素并移除
    var c = a.pop();
    // 返回删除的元素
    console.log(c);
    // 返回头部元素并删除
    var d = a.shift();
    // 元素添加到头部
    a.shift('七万');

    // 数组合并
    var arr1 = [1, 2, 3];
    var arr2 = [3, 4];
    // 原数组不改变,产生新的数组
    var arr3 = arr1.concat(arr2);
    console.log(arr1, arr2, arr3);
    // 可以拼接数组和单个元素
    var arr4 = arr1.concat(arr2, 7, 8, 9);

    // 数组拆分
    var arr5 = [0, 1, 2, 3, 4, 5];
    // 开始位置0,结束位置3,包头不包尾,结束位置不写表示截到末尾
    var arr6 = arr5.slice(0, 3);
    console.log(arr6);
    // 3, 4
    var arr7 = arr5.slice(-3, -1); */

    // 6.数组其他方法
/*     var arr = [0, 1, 2, 3, 4, 5];
    // 直接操作原数组, 3为元素数量
    arr.splice(0, 3);
    console.log(arr)
    // 替换元素,个数没必要一一对应
    arr.splice(0, 2, 'haha', 'xixi');
    // 添加元素
    arr.splice(3, 0, 'haha');
    // 倒序
    arr.reverse();
    // 排序,可以对字符串进行排序
    // sort默认是按照字符编码顺序排
    arr.sort();
    // 数字排序,自定义比较器
    arr.sort(function(a, b) {
        // if(a>b) {
        //     return 1;
        // } else if(a<b) {
        //     return -1;
        // } else {
        //     return 0;
        // }
        return a-b;
        // 倒序
        // return b-a;
    });
    // 数组转为字符串,默认以,作为分隔符
    var str = arr.join();
    console.log(str); */

    // 7.字符串方法
/*     var str = '一曲肝肠断,天涯何处觅知音';
    // 不论中英文,都算一个长度
    console.log(str.length);
    // 指定位置字符
    console.log(str.charAt(1));
    // 字符串拼接,返回新串,原串不变
    var str2 = str.concat('hello');
    console.log(str, str2);
    // 索引,如果出现多次,返回首次出现位置
    str.indexOf('肝肠');
    // 最后一次出现的位置
    str.lastIndexOf('天');
    // 字符串切片,包头不包尾
    var substr = str.slice(0, 3);
    // 切分成数组,空串作为分割符切分成单个字符数组
    str.split(',');
    // 子串 开始位置 结束位置
    str.substring(0, 5);
    // 开始索引,长度
    str.substr(0, 5);
    var str1 = "Hello World!";
    // 转换大写
    var strUpper = str1.toUpperCase();
    // 转化小写
    var strLower = str1.toLowerCase(); */

    // 8.IIFE即时调用表达式
    // 定义时立即执行
    // 降级为函数表达式,+或者-,不常用
    +function haha() {
        console.log('haha');
    }();
    // 常用,匿名函数,不能用名称调用
    (function iife(){
        console.log("iife匿名函数");
    })();

    // 9.通过数组观察闭包
/*     var arr = [];
    for(var i=0; i<10; i++) {
        arr[i] = function() {
            console.log(i);
        };
    }
    arr[6]();
    // 调用时再去寻找i
    arr[9](); */

    // 解决闭包造成的变量问题
/*     var arr = [];
    for(var i=0; i<10; i++) {
        (function(m) {
            arr[m] = function() {
                console.log(m);
            }
        })(i);
    }
    arr[6](); */

</script>  
3.dom
<body>
    <p id="box" class="box">ppp</p>
    <img id="huge" src="img/huge.jpg" alt="">
    <div class="box2" id="box2"></div>
    <script>
        var box = document.getElementById('box');
        console.log(box);
        // 对象类型
        console.log(typeof box)
        box.style.background = 'red';
        var haha = document.getElementById('haha');
        // 找不到,null
        console.log(haha);
        // id需要唯一,ie7及较低版本会把name也当成id

        var huge = document.getElementById('huge');
        // 直接修改属性
        huge.src = 'img/hg.jpg';
        // 获取属性
        var hugeSrc = huge.src;
        console.log(hugeSrc);
        // 获取class时需要写成className,class是系统保留字
        // label的for要改成htmlFor
        var box2 = document.getElementById('box2');
        console.log(box2.className);
        box2.className = 'haha';

        // 通过getAttribute方式获取属性值
        console.log(box.getAttribute('class'));
        box.setAttribute('class', 'xixi');
        // 通过.语法无法获取自定义属性
        // .语法获取的是属性对象,get方式获取的是字符串
        console.log(box.style.background);
    </script>
</body>
4.事件
    <script>
        var box = document.getElementById('box');
        // box.onclick = function() {
        //     alert('点击box');
        // };
        // box.onclick = haha;

        // function haha() {
        //     alert('haha');
        // }

        // onfocus获得焦点
        // onblur失去焦点
        box.onclick = function() {
            console.log('点击');
        };
        box.onmouseover = function() {
            console.log('鼠标移入');
        };
        box.onmouseout = function() {
            console.log('鼠标移出');
        };
        box.onmousedown = function() {
            console.log('鼠标按下');
        };
        box.onmouseup = function() {
            console.log('鼠标抬起');
        };
        box.ondblclick = function() {
            console.log('双击');
        };
        window.onload = function() {
            console.log('页面加载完毕触发事件');
        };

        var input = document.getElementById('ipt');
        input.onfocus = function() {
            console.log('获得焦点');
        };
    </script>
事件练习-调色盘

点击 +-按钮分别修改rgb值以改变body背景色
通过输入rgb值修改body背景色

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            background-color: rgb(33,44,55);
        }
    </style>
</head>
<body id="body">
    <p>
        r:<button id="rm">-</button>
        <input type="text" value="33" id="r">
        <button id="rp">+</button>
    </p>
    <p>
        g:<button id="gm">-</button>
        <input type="text" value="44" id="g">
        <button id="gp">+</button>
    </p>
    <p>
        b:<button id="bm">-</button>
        <input type="text" value="55" id="b">
        <button id="bp">+</button>
    </p>
    <button id="go">go</button>
    <script>
        var rm = document.getElementById('rm');
        var rp = document.getElementById('rp');
        var gm = document.getElementById('gm');
        var gp = document.getElementById('gp');
        var bm = document.getElementById('bm');
        var bp = document.getElementById('bp');
        var go = document.getElementById('go');
        var rtext = document.getElementById('r');
        var gtext = document.getElementById('g');
        var btext = document.getElementById('b');
        var body = document.getElementById('body');

        // 信号量
        var r = 33;
        var g = 44;
        var b = 55;

        // 点击事件
        rm.onclick = function () {
            // 信号量改变
            r--;
            changeColor();
        }

        rp.onclick = function () {
            r++;
            changeColor();
        }

        gm.onclick = function () {
            g--;
            changeColor();
        }

        gp.onclick = function () {
            g++;
            changeColor();
        }

        bm.onclick = function () {
            b--;
            changeColor();
        }

        bp.onclick = function () {
            b++;
            changeColor();
        }

        function changeColor() {
            // 信号量判断
            if(r<0) r = 0;
            if(g<0) g = 0;
            if(b<0) b = 0;
            if(r>255) r = 255;
            if(g>255) g = 255;
            if(b>255) b = 255;
            rtext.value = r;
            gtext.value = g;
            btext.value = b;
            body.style.backgroundColor = 'rgb('+ r +','+ g +','+ b +')';
        }

        // 根据用户输入的数据改变颜色
        go.onclick = function () {
             r = rtext.value;
             g = gtext.value;
             b = btext.value;
             changeColor();
        }
    </script>
</body>
</html>
练习:表格隔行变色
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table {
            width: 800px;
            height: 600px;
            border: 1px solid black;
            border-collapse: collapse;
        }

        td {
            border: 1px solid black;
            border-collapse: collapse;
        }
    </style>
</head>
<body>
<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>
<script>
    var trs = document.getElementsByTagName('tr');
    for(var i=0; i<trs.length; i+=2) {
        trs[i].style.backgroundColor = 'red';
    }
    // 类似地可以做到隔列变色
</script>
</body>
</html>
练习:批量添加监听

为每个p标签添加点击事件,注意闭包变量问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        p{
            width: 100px;
            height: 100px;
            float: left;
            background: skyblue;
            margin-right: 10px;
        }
    </style>
</head>
<body>
<p>0</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<script>
    var ps = document.getElementsByTagName('p');
/*    for(var i=0; i<ps.length; i++) {
        ps[i].onclick = function() {
            console.log(i);
        }
    }*/
    // 闭包问题解决
/*    for(var i=0; i<ps.length; i++) {
        // IIFE
        (function (m) {
            ps[m].onclick = function() {
                console.log(m);
            }
        })(i);
    }*/
    for(var i=0; i<ps.length; i++) {
        // 绑定自定义属性
        ps[i].idx = i;
        ps[i].onclick = function() {
            // console.log(this);
            console.log(this.idx);
        }
    }
</script>
</body>
</html>
练习:对应

点击上方的P元素,对应的下方P元素修改背景色


效果
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width: 600px;
            height: 100px;
            border: 1px solid #ddd;
        }
        p{
            width: 80px;
            height: 80px;
            margin: 10px;
            background: skyblue;
            float: left;
        }
    </style>
</head>
<body>
<div>
    <p>0-1</p>
    <p>0-2</p>
    <p>0-3</p>
    <p>0-4</p>
    <p>0-5</p>
    <p>0-6</p>
</div>
<div>
    <p>1-1</p>
    <p>1-2</p>
    <p>1-3</p>
    <p>1-4</p>
    <p>1-5</p>
    <p>1-6</p>
</div>
<script>
    var ps0 = document.getElementsByTagName('div')[0].getElementsByTagName('p');
    var ps1 = document.getElementsByTagName('div')[1].getElementsByTagName('p');

    for (var i = 0; i < ps0.length; i++) {
        // 绑定自定义属性
        ps0[i].idx = i;
        ps0[i].onclick = function () {
            ps1[this.idx].style.background = 'red';
        }
    }
</script>
</body>
</html>
练习:排他

点击P元素,修改其背景色,其他P元素恢复原色
应用场景:轮播图切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        p{
            width: 100px;
            height: 100px;
            background: skyblue;
            float: left;
            margin-right: 10px;
        }
    </style>
</head>
<body>
<p>0</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<script>
    var ps = document.getElementsByTagName('p');
    for (var i = 0; i < ps.length; i++) {
        ps[i].onclick = function () {
            // 把所有的背景色改为原来的
            for(var j = 0; j < ps.length; j++) {
                ps[j].style.background = 'skyblue';
            }
            this.style.background = 'red';
        }
    }
</script>
</body>
</html>
获取计算后样式

通过.语法无法获得外部样式,这里采用window.getComputedStyle方式获取计算后样式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 200px;
            height: 200px;

        }
    </style>
</head>
<body>
<div id="idbox" class="box" style="background: red;"></div>
<script>
    var box = document.getElementById('idbox');
    // 无法通过.语法获得外部样式
    // console.log(box.style.width);
    // console.log(box.style.background);
    // 样式对象
    console.log(window.getComputedStyle(box));
    // window.可以省略
    console.log(getComputedStyle(box));
    // 获取计算后样式
    console.log(window.getComputedStyle(box).getPropertyValue('width'));
    // 通过中括号方式获取样式
    console.log(getComputedStyle(box)['height']);
</script>
</body>
</html>
4.事件实例
轮播图
效果图
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            width: 672px;
            height: 320px;
            border: 1px solid #ddd;
            margin: 100px auto;
            position: relative;
        }
        ul{
            list-style: none;
        }
        .imgList ul li{
            width: 672px;
            height: 320px;
            position: absolute;
            top: 0;
            left: 0;
            /*默认全部隐藏*/
            display: none;
        }

        .imgList ul li.current{
            display: block;
        }

        .btn span{
            width: 55px;
            height: 55px;
            background: url('img/sohu/slide-btnL.png');
            position: absolute;
            top: 50%;
            margin-top: -27.5px;
        }
        .btn span.leftBtn {
            left: 10px;
        }
        .btn span.rightBtn {
            right: 10px;
            background: url('img/sohu/slide-btnR.png');
        }
        .circle{
            position: absolute;
            bottom: 10px;
            right: 10px;
        }
        .circle ul li{
            width: 10px;
            height: 10px;
            background: rgba(0,0,0,.5);
            border-radius: 50%;
            float: left;
            margin-left: 10px;
        }

        .circle ul li.current{
            background: rgb(255,255,255);
        }
    </style>
</head>
<body>
<div class="box">
    <div class="imgList" id="imgList">
        <ul>
            <li class="current"><a href="#"><img src="img/sohu/aaa.jpg" alt=""></a></li>
            <li><a href="#"><img src="img/sohu/bbb.jpg" alt=""></a></li>
            <li><a href="#"><img src="img/sohu/ccc.jpg" alt=""></a></li>
            <li><a href="#"><img src="img/sohu/ddd.jpg" alt=""></a></li>
            <li><a href="#"><img src="img/sohu/eee.jpg" alt=""></a></li>
        </ul>
    </div>
    <div class="btn">
        <span class="leftBtn" id="left"></span>
        <span class="rightBtn" id="right"></span>
    </div>
    <div class="circle" id="circle">
        <ul>
            <li class="current"></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div>
</div>
<script>
    var imgList = document.getElementById('imgList').getElementsByTagName('li');
    var left = document.getElementById('left');
    var right = document.getElementById('right');
    var circle = document.getElementById('circle').getElementsByTagName('li');
    var idx = 0;
    right.onclick = function () {
        idx++;
        changePic();
    }

    left.onclick = function () {
        idx--;
        changePic();
    }

    /* 小圆点批量监听 */
    for (var i = 0; i < circle.length; i++) {
        // 绑定自定义属性
        circle[i].idxx = i;
        circle[i].onmouseover = function () {
            // 鼠标进入小圆点,更改信号量的值
            idx = this.idxx;
            changePic();
        }
    }
    
    function  changePic() {
        if(idx > imgList.length - 1) {
            idx = 0;
        }
        if(idx < 0) {
            idx = imgList.length - 1;
        }
        // 根据信号量做排他
        for (var i = 0; i < imgList.length; i++) {
            imgList[i].className = '';
        }
        imgList[idx].className = 'current';

        // 根据信号量做排他
        for (var i = 0; i < circle.length; i++) {
            circle[i].className = '';
        }
        circle[idx].className = 'current';
    }
</script>
</body>
</html>
获取计算后样式的浏览器兼容问题
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background: #ddd;
        }
    </style>
</head>
<body>
<div class="box" id="idbox" style="border: 10px solid red;"></div>
<script>
    var box = document.getElementById('idbox');
    // 获取样式
    console.log(box.style.border);
    console.log(window.getComputedStyle(box));
    // 获取计算后样式
    console.log(getComputedStyle(box).getPropertyValue('width'));
    console.log(getComputedStyle(box).getPropertyValue('border'));
    console.log(getComputedStyle(box)['border']);
    // 低版本ie不支持
    alert(getComputedStyle(box)['width']);


    // ie获取计算后样式,这种方式chrome会报错
    // alert(box.currentStyle);
    // alert(box.currentStyle.width);
    // alert(box.currentStyle['height']);
    // 下划线改驼峰
    // alert(box.currentStyle.fontSize);
</script>
</body>
</html>
浏览器能力检测
<script>
    var box = document.getElementsByTagName('div')[0];
    // 能力检测
    if(window.getComputedStyle) {
        console.log('可以获取');
    } else {
        alert('无法获取');
        alert(box.currentStyle['width'])
    }
</script>
</body>
透明度兼容问题
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background: red;
            opacity: 0.5;
            /* 透明度适配ie */
            filter: alpha(opacity=50);
        }
    </style>
</head>
<body>
<div class="box" id="idbox"></div>
<script>
    var box = document.getElementById('idbox');
    var touming = 0.3;
    box.style.opacity = touming;
    box.style.filter = 'alpha(opacity='+ touming*100 +')';
</script>
</body>
</html>
定时器
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            background: skyblue;
            position: absolute;
            top: 100px;
            left: 100px;
        }
    </style>
</head>
<body>
<div class="box" id="idbox"></div>
<button id="move">move</button>
<button id="stop">stop</button>
<script>
    // window方法都可以省略window.
    // window.setInterval(function () {
/*    setInterval(function () {
        // 每隔1秒执行一次
        console.log(Math.random());
    }, 1000);*/
    // 引用外部函数
    // setInterval(fun, 1000);

    /* 函数声明可以写在外部 */
/*    function fun() {
        console.log(Math.random());
    }*/
    var box = document.getElementById('idbox');
    var move = document.getElementById('move');
    var stop = document.getElementById('stop');

    var nowLeft = 100;
    // 全局定时器
    var timer;
    move.onclick = function () {
        nowLeft += 10;
        // box.style.left = nowLeft + 'px';
        timer = setInterval(function () {
            nowLeft += 10;
            box.style.left = nowLeft + 'px';
        }, 50);
    };

    stop.onclick = function () {
        // 清除定时器
        clearInterval(timer);
    };
</script>
</body>
</html>
运动注意的问题

设表先关和拉钟停表

var box = document.getElementsByTagName('div')[0];
    // 信号量
    var nowLeft = 100;
    var timer;
    timer = setInterval(function () {
        // 设表先关
        clearInterval(timer);
        nowLeft += 13;
        // 拉钟停表
        if(nowLeft > 600) {
            nowLeft = 600;
            clearInterval(timer);
        }
        console.log(nowLeft);
        box.style.left = nowLeft + 'px';
    }, 50);
无缝连续滚动
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .box{
            width: 800px;
            height: 130px;
            border: 10px solid #ddd;
            margin: 0px auto;
            position: relative;
            overflow: hidden;
        }
        .move{
            width: 10000px;
            background: skyblue;
            position: absolute;
            top: 0;
            left: 0;
        }
        ul {
            overflow: hidden;
        }
        li {
            list-style: none;
            width: 200px;
            height: 130px;
            float: left;
            margin-right: 10px;
        }
    </style>
</head>
<body>
<div class="box">
    <div class="move" id="move">
        <ul>
            <li><a href="#"><img src="img/shuzi/0.png" alt=""></a></li>
            <li><a href="#"><img src="img/shuzi/1.png" alt=""></a></li>
            <li><a href="#"><img src="img/shuzi/2.png" alt=""></a></li>
            <li><a href="#"><img src="img/shuzi/3.png" alt=""></a></li>
            <li><a href="#"><img src="img/shuzi/4.png" alt=""></a></li>
            <li><a href="#"><img src="img/shuzi/5.png" alt=""></a></li>
        </ul>
    </div>
   
</div>
<script>
    var move = document.getElementById('move');
    var imgul = move.getElementsByTagName('ul')[0];
    // 图片复制一份
    imgul.innerHTML += imgul.innerHTML;
    // 信号量
    var nowLeft = 0;
    var timer;
    
    ani();

    function ani() {
        timer = setInterval(function () {
            nowLeft -= 10;
            if(nowLeft <= -1260) {
                newLeft = 0;
            }
            move.style.left = nowLeft + 'px';
        }, 50);
    }

    // 鼠标进入停止轮播
    move.onmouseover = function () {
        clearInterval(timer);
    }
    // 鼠标离开继续轮播
    move.onmouseout = function () {
        ani();
    }
</script>
</body>
</html>
5.滚轮事件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>滚轮事件</title>
    <style>
        body{
            height: 2000px;
        }
        .box{
            width: 200px;
            height: 200px;
            background: skyblue;
        }
    </style>
</head>
<body>
<div class="box" id="idbox"></div>
<script>
    // TODO
    var box = document.getElementById('idbox');

    function mouseWheelHandler(event) {
        event = event || window.event;
        if(event.wheelDelta) {
            direction = event.wheelDelta > 0 ? 1 : -1;
        } else {
            // 兼容方向
            direction = event.wheelDelta < 0 ? 1 : -1;
        }
        box.innerHTML = direction;
    }
    box.onmousewheel = mouseWheelHandler;

    // 火狐
    try{
        box.addEventListener('DOMMouseScroll', mousewheelHandler, false);
    }catch(error){

    }
</script>
</body>
</html>
6.对象
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>对象</title>
    <style>
        div {
            height: 100px;
            width: 100px;
            background: skyblue;
        }
    </style>
</head>
<body>
<div></div>
<script>
    // 对象,json key加引号为了后台兼容
    // key中包含数字 特殊字符必须加引号
/*    var obj = {
        name: 'zhangsan',
        age: 18,
        gender: 'male',
        '123': 'haha'
    };
    console.log(typeof obj);
    // 属性无序集合
    console.log(obj['age']);
    console.log(obj['123']);*/

    // new
/*    var obj2 = new Object();
    console.log(typeof obj2);
    // 添加属性
    obj2.age = 20;
    obj2.name = 'lisi';
    console.log(obj2);*/

    // 属性值可以是函数和数组
/*    var obj = {
        age: 18,
        pai: ['东', '西', '南'],
        sayhi: function () {
            this.age++;
            console.log('hi');
        }
    }
    console.log(obj.sayhi);
    obj.sayhi();*/
    // 单纯的一个函数中this代表window对象


    function haha() {
        console.log(this);
    }

    var div = document.getElementsByTagName('div')[0];
    // 点击事件中this指向当前元素
    div.onclick = haha;


</script>
</body>
</html>
构造函数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
/*    var xiaoming = {
        name: 'xiaoming',
        sayHi: function() {
            console.log('hi, 我叫' + this.name);
        }
    };
    xiaoming.sayHi();

    var xiaohong = {
        name: 'xiaohong',
        sayHi: function() {
            console.log('hi, 我叫' + this.name);
        }
    }
    xiaohong.sayHi();*/

    // 类
    function People(name) {
        this.name = name;
        this.sayHi = function () {
            console.log('hi, 我叫' + this.name);
        };
    }

    var xiaoming = new People('xiaoming');
    var xiaohong = new People('xiaohong');

    xiaoming.sayHi();
</script>
</body>
</html>
女孩行走效果
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>女孩行走效果</title>
    <style>
        div{
            width: 79px;
            height: 108px;
            /*border: 1px solid #ddd;*/
            background: url('img/girl.png') no-repeat;
            background-position: -79px -216px;
            position: absolute;
            /*top: 100px;*/
            /*left: 100px;*/
        }
    </style>
</head>
<body>
<!--<div class="box" id="idbox"></div>-->

<script>
    function Girl(left, top) {
        this.left = left;
        this.top = top;

        /*创建方法*/
        this.init = function () {
            // 创建div节点
            this.dom = document.createElement('div');
            // 拼接到body
            document.body.appendChild(this.dom);
            // 设置位置
            this.dom.style.left = this.left + 'px';
            this.dom.style.top = this.top + 'px';
        };

        /*移动方法*/
        this.move = function () {
            var idx = 0;
            var self = this;
            this.timer = setInterval(function () {
                idx ++;
                if(idx > 7) {
                    idx = 0;
                }
                self.left += 5;
                if(self.left >= 666) {
                    self.die();
                    // timer.clearInterval();
                }
                // 注意this的指代
                self.dom.style.left = self.left + 'px';
                self.dom.style.backgroundPosition = -79*idx + 'px -216px';
            }, 50);
        }

        /*销毁方法*/
        this.die = function () {
            clearInterval(this.timer);
            document.body.removeChild(this.dom);
        }

        // 调用创建方法
        this.init();
        // 调用移动方法
        this.move();
    }

    // new Girl(300, 400);
    // new Girl(100, 100);
    // new Girl(300, 300);
    setInterval(function () {
        new Girl(100, parseInt(Math.random() * 500));
    }, 500);
</script>
</body>
</html>
7.原型
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function haha() {
        console.log('haha');
    }
    console.log(haha.prototype);
    // 原型是对象类型
    console.log(typeof haha.prototype);
    // 普通函数原型没啥用

    function People(name, age) {
        this.name = name;
        this.age = age;
    }

    var xiaoming = new People('xiaoming', 20);
    console.log(xiaoming.gender);

    People.prototype = {
        gender: 'male'
    };

    var xiaohong = new People('xiaohong', 18);
    console.log(xiaohong.gender);
    // 原型对象
    console.log(xiaohong.__proto__ == People.prototype);
</script>
</body>
</html>
constructor
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>原型链</title>
</head>
<body>
<script>
    function People(name, age) {
        this.name = name;
        this.age = age;
    }

    People.prototype.say = function () {
        console.log(this.name + ',' + this.age);
    };
    // 已有属性
    People.prototype.name = 'haha';
    // 原型的构造函数指向原构造函数
    console.log(People.prototype.constructor);

    var xiaoming = new People('xiaoming', 20);
    // 对象实例的构造函数也指向原构造函数
    console.log(xiaoming.constructor);
    // true
    // 对象实例通过原型对象寻找构造函数
    console.log(xiaoming.constructor == People.prototype.constructor);
    // 已有属性不去原型中找
    console.log(xiaoming.name);
</script>
</body>
</html>
原型链
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>原型链</title>
</head>
<body>
<script>
    function People() {

    }
    People.prototype.say = function () {
        console.log('hi');
    };
    var xiaoming = new People();
    console.log(xiaoming.__proto__ == People.prototype);
    // 原型对象的原型对象,上溯到Object()
    console.log(xiaoming.__proto__.__proto__.constructor);
    // 会去原型对象的原型对象寻找方法
    console.log(xiaoming.toString());
</script>
</body>
</html>
原型链-其他类型
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>原型链_其他类型</title>
</head>
<body>
<script>
    // 数组原型
/*    var arr = [1, 2, 3];
    console.log(arr.__proto__.constructor);
    // 数组的原型为object
    console.log(arr.__proto__.__proto__.constructor);*/

    // 函数原型
    function People() {

    }
    // 函数的构造函数
    console.log(People.__proto__.constructor);
    // 函数的构造函数的原型为object
    console.log(People.__proto__.__proto__.constructor);
    console.log(People.__proto__ == Function.prototype);

    // Function原型绑定方法,People可以调用
    Function.prototype.haha = function () {
        console.log('haha');
    }
    People.haha();

    // 其他函数也可调用
    function Dog() {

    }
    Dog.haha();
</script>
</body>
</html>
数组添加方法
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>数组添加方法</title>
</head>
<body>
<script>
/*    var arr = [1, 23, 333, 444];
    var max = -Infinity;
    for(var i=0; i<arr.length; i++) {
        if(arr[i] > max) {
            max = arr[i];
        }
    }
    console.log(max);*/

    var arr = [1, 23, 333, 444];
    // 数组添加方法
    Array.prototype.maxCount = function() {
        var max = -Infinity;
        for(var i=0; i<arr.length; i++) {
            if(arr[i] > max) {
                max = arr[i];
            }
        }
        return max;
    }
    console.log(arr.maxCount());
</script>
</body>
</html>
in运算符
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>in</title>
</head>
<body>
<script>
    var obj = {
        a: 1,
        b: 2,
        c: 3
    };
    console.log('a' in obj);
    console.log('b' in obj);
    console.log('d' in obj);

    // 遍历json用for in
    // in判断属性是否是对象属性,会在原型链上查找
    obj.__proto__.d = 'male';
    console.log('d' in obj);

    for(var k in obj) {
        console.log(k);
    }
</script>
</body>
</html>
8.BOM

DOM是BOM的子集,BOM处理页面之间的行为

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>BOM</title>
</head>
<body>
<script>
    // var a = 100;
    // console.log(a);
    // a作为window的属性
    console.log(window);
    // window的方法可以省略window.
    // window.alert('haha');

    // name是window的自带属性,不要声明var
    // name与cookie类似,2MB,可以解决跨域
    window.name = 'haha';
    console.log(window.name);


    // 尺寸相关
/*    // 浏览器窗口大小
    console.log(window.outerHeight);
    console.log(window.outerWidth);

    // 视口大小,包括滚动条
    console.log(window.innerHeight);
    console.log(window.innerWidth);

    // 不包含滚动条
    console.log(document.documentElement.clientHeight);
    console.log(document.documentElement.clientWidth);*/

    // navigator-浏览器相关
/*    console.log(window.navigator);
    // 内核相关
    console.log(window.navigator.userAgent);*/

    // 历史相关
    window.history.back();
    // window.history.forward();
    // 跳转到栈中指定页面
    // window.history.go(2);
    // 从当前页面开始算
    console.log(window.history.length);
</script>
</body>
</html>
9.正则
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
    // 在aabbccabc中查找abc,匹配一次
    // console.log(/abc/.exec('aabbccabc'));

    // test测试能否匹配到
    // console.log(/abc/.test('aabbccabc'));

    // 正则表达式规则
    // 转义
    // console.log(/\[/.test('ab[c'));
    // 精确匹配
    // console.log(/abc/.test('abcde'));
    // 空白字符 匹配tab
    // console.log(/\s/.test(' '));
    // console.log(/\s/.test(`
    // `));
    // 字符集
    // console.log(/[a[bd]c/.test('abcde'));
    // 范围
    // console.log(/1[a-z]2/.test('1a2'));
    // 负向
    // console.log(/a[^a-z]c/.test('a0c'));
    // 组合 [a-zA-Z0-9]匹配字母数字
    // console.log(/[a[a-zA-Z]c/.test('a0c'));
    // 修饰符 /g全局搜索
    // console.log('12abc'.match(/[a-z]/g));
    // console.log('aac12abc'.match(/a[a-z]c/g));
    // 忽略大小写
    console.log(/[a]/i.test('A'));
</script>
</body>
</html>

相关文章

  • 前端-02-js

    1.语法基础 2.函数 3.dom 4.事件 事件练习-调色盘 点击 +-按钮分别修改rgb值以改变body背景色...

  • 02-js基础语法

    //1. js中的注释//这是单行注释/*这个是多行注释*/ //2.语句//一条语句结束需要加分号(现在的js版...

  • 02-JS基础(内置对象)

    javascript基础二 内置预设对象: Date() 返回当前时间和日期 getDate() 返回一个月中的某...

  • 02-JS基础-数据类型

    数据的计量单位 数据类型 JS中的六种数据类型 String    字符串 (基本数据类型)Number   数...

  • 02-JS常见输出方式

    1.通过弹窗的形式来输出alert(需要输出的内容);confirm(需要输出的内容);prompt(需要输出的内...

  • [JavaScript30 笔记] 02-JS + CSS Cl

    写在系列开篇 在学习了基本的 HTML / CSS / JavaScript 之后没有啥 side project...

  • 前端文章系列

    【前端】从0.1开始,创建第一个项目 【前端】初识HTML 【前端】HTML标签 【前端】HTML属性 【前端】C...

  • Web前端小白入门指迷

    大前端之旅 大前端有很多种,Shell 前端,客户端前端,App 前端,Web 前端和可能接下来很会火起来的 VR...

  • 推荐几个好的前端博客和网站

    前端开发博客前端开发博客-前端开发,前端博客 对前端知识结构的理解人类身份验证 - SegmentFault 脚本...

  • 2020-04-11

    前端工程化相关 前端动画相关 优化前端性能

网友评论

      本文标题:前端-02-js

      本文链接:https://www.haomeiwen.com/subject/gpsnsktx.html