美文网首页
第二周总结

第二周总结

作者: 魅影_0d2e | 来源:发表于2018-11-12 19:35 被阅读0次

    一、主页

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
            <style>
                * { font-size: 18px; }
                h2 { font-size: 22px; }
                h3 { font-size: 20px; }
                ul li { list-style: circle; }
            </style>
        </head>
        <body>
            <h2>JavaScript课堂案例</h2>
            <hr>
            <h3>Make English as your working language!!!</h3>
            <h3>浏览器中的JavaScript:</h3>
            <ul>
                <li>ECMAScript: JavaScript语法规范</li>
                <li>BOM: 浏览器对象模型(Browser Object Model),把浏览器当成一个对象(window),通过这个对象可以操控浏览器</li>
                <li>DOM: 文档对象模型(Document Object Model),把整个页面当成一个对象(document),通过这个对象可以操作整个页面</li>
            </ul>
            <hr>
            <h3>课堂案例</h3>
            <ol>
                <li><a href="example01.html">例子1:BOM和DOM的感性认识</a></li>
                <li><a href="example02.html">例子2:成都机动车限行查询</a></li>
                <li><a href="example03.html">例子3:延迟跳转到百度</a></li>
                <li>
                    <a href="example04.html">例子4:轮播广告</a>
                    <span><a href="#homework01">完整效果请参考作业1</a></span>
                </li>
                <li><a href="example05.html">例子5:事件冒泡和事件捕获</a></li>
                <li><a href="example06.html">例子6:获取事件源和访问相关元素</a></li>
                <li><a href="example07.html">例子7:动态添加和删除元素</a></li>
                <li><a href="example08.html">例子8:流氓浮动广告</a></li>
                <li><a href="example09.html">例子9:jQuery实现表格效果</a></li>
                <li><a href="example10.html">例子10:jQuery实现动态列表</a></li>
                <li><a href="example11.html">例子11:Ajax加载美女图片(原生JavaScript)</a></li>
                <li><a href="example12.html">例子12:Ajax加载美女图片(jQuery)</a></li>
            </ol>
            <h3>课后练习</h3>
            <ol>
                <li>
                    <a name="homework01"></a>
                    <a href="homework01.html">练习1:轮播广告</a>
                </li>
                <li><a href="homework02.html">练习2:缩略图效果</a></li>
                <li><a href="homework03.html">练习3:闪烁的方块</a></li>
                <li><a href="homework04.html">练习4:表格效果</a></li>
                <li><a href="homework05.html">练习5:购物车效果</a></li>
                <li><a href="homework06.html">练习6:可拖拽的元素</a></li>
            </ol>
        </body>
    </html>
    

    二、BOM和DOM的感性认识

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
            <style>
                h1 { font: 72px arial; }
                #bar { color: red; }
                .foo { color: green; }
                h1 { color: blue !important; }
                #timer {
                    width: 250px;
                    height: 30px;
                    line-height: 30px;
                    text-align: center;
                    color: yellow;
                    background-color: blue;
                    float: right;
                }
            </style>
        </head>
        <body>
            <div id="timer"></div>
            <h1 id="bar" class="foo">Hello, world!</h1>
            <button onclick="shutdown()">关闭</button>
            <button onclick="openBaidu()">打开百度</button>
            <script>
                function openBaidu() {
                    window.open('https://www.baidu.com', '', 
                        'width=300,height=200');
                }
                
                function shutdown() {
                    if (window.confirm('确定要退出吗?')) {
                        window.close();
                    }
                }
                
                var weekdays = ['日', '一', '二', '三', '四', '五', '六'];
                
                function showTime() {
                    var now = new Date();
                    var year = now.getFullYear();
                    var month = now.getMonth() + 1;
                    var date = now.getDate();
                    var hour = now.getHours();
                    var minute = now.getMinutes();
                    var second = now.getSeconds();
                    var day = now.getDay();
                    var timeStr = year + '年' +
                        (month < 10 ? '0' : '') + month + '月' +
                        (date < 10 ? '0' : '') + date + '日 ' +
                        (hour < 10 ? '0' : '') + hour + ':' +
                        (minute < 10 ? '0' : '') + minute + ':' +
                        (second < 10 ? '0' : '') + second +
                        ' 星期<b>' + weekdays[day] + '</b>';
                    var div = document.getElementById('timer');
                    div.innerHTML = timeStr;
                }
                
                showTime();
                window.setInterval(showTime, 1000);
                    
    //          1TBS风格 - C/Unix - Dennis M. Ritchie
    //          Allman风格 - FreeBSD - Allman
    //          while循环 / do-while循环 / for循环
    //          while循环 - 不确定循环的次数
    //          for循环 - 循环的次数是确定的
    //          do-while循环 - 至少执行一次
    //          var flag = true;
    //          do {
    //              var yearStr = window.prompt('请输入年份: ');
    //              var year = parseInt(yearStr);
    //              if (year == yearStr && year > 0) {
    //                  if (year % 4 == 0 && year % 100 != 0
    //                      || year % 400 == 0) {
    //                      window.alert(year + '年是闰年');
    //                  } else {
    //                      window.alert(year + '年不是闰年');
    //                  }
    //                  flag = window.confirm('是否继续?');
    //              } else {
    //                  window.alert('请输入有效的年份!');
    //              }
    //          } while (flag);
            </script>
        </body>
    </html>
    

    三、成都机动车限行查询

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>成都机动车限行查询</title>
            <style>
                #search {
                    width: 640px;
                    margin: 0 auto;
                    text-align: center;
                    margin-top: 150px;
                }
                #carno {
                    display: inline-block;
                    width: 460px;
                    height: 36px;
                    font: 36px/36px arial;
                    text-align: center;
                    vertical-align: middle;
                    border: none;
                    outline: none;
                    border-bottom: 1px dotted darkgray;
                }
                #search input[type=button] {
                    width: 80px;
                    height: 36px;
                    font: 28px/36px arial;
                    border: none;
                    color: white;
                    background-color: red;
                    vertical-align: middle;
                }
                #result {
                    width: 640px;
                    margin: 0 auto;
                    text-align: center;
                    font: 32px/36px arial;
                }
            </style>
        </head>
        <body>
            <div id="search">
                <input type="text" id="carno" placeholder="请输入车牌号">
                <input type="button" value="查询" onclick="showResult()">
                <input type="button" value="清除" onclick="clearResult()">
            </div>
            <hr>
            <p id="result"></p>
            <script>
                var p = document.getElementById('result');
                
                function clearResult() {
                    p.textContent = '';
                }
                
                function showResult() {
                    var input = document.getElementById('carno');
                    var carNo = input.value;
                    var regex = /^[京津沪渝辽吉黑冀鲁豫晋陕甘闽粤桂川云贵苏浙皖湘鄂赣青新宁蒙藏琼][A-Z]\s*[0-9A-Z]{5}$/;
                    if (regex.test(carNo)) {
                        var digitStr = lastDigit(carNo);
                        if (digitStr) {
                            var digit = parseInt(digitStr);
                            var day = new Date().getDay();
                            if (digit % 5 == day || digit % 5 == day - 5) {
                                p.innerHTML = carNo + '今日限行<br>' + p.innerHTML;
                            } else {
                                p.innerHTML = carNo + '今日不限行<br>' + p.innerHTML;
                            }
                        } else {
                            p.innerHTML = carNo + '不是有效的车牌号<br>' + p.innerHTML; 
                        }
                    } else {
                        p.innerHTML = carNo + '不是有效的车牌号<br>' + p.innerHTML; 
                    }
                    input.value = '';
                }
                
                function lastDigit(str) {
                    for (var index = str.length - 1; index >= 0; index -= 1) {
                        var digitStr = str[index];
                        if (digitStr >= '0' && digitStr <= '9') {
                            return digitStr;
                        }
                    }
                    return null;
                }
            </script>
        </body>
    </html>
    

    四、延迟跳转

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>延迟跳转</title>
        </head>
        <body>
            <h3><span id="counter">5</span>秒钟以后自动跳转到百度</h3>
            <script>
                var countDown = 5;
                var span = document.getElementById('counter');
                window.setTimeout(function() {
                    countDown -= 1;
                    if (countDown == 0) {
                        // window对象的location属性代表浏览器地址栏
                        window.location.href = 'https://www.baidu.com';
                    } else {
                        span.textContent = countDown;
                        // arguments是函数中的隐含对象
                        // 通过arguments[0]、arguments[1]可以获得函数的参数
                        // 通过arguments.callee可以获得正在被调用的函数
                        window.setTimeout(arguments.callee, 1000);
                    }
                }, 1000);
                
            </script>
        </body>
    </html>
    

    五、轮播广告

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
            <style>
                #adv {
                    width: 705px;
                    margin: 0 auto;
                }
            </style>
        </head>
        <body>
            <div id="adv">
                <img src="img/slide-1.jpg" alt="" width="705">
            </div>
            <script>
                var index = 0;
                var images = ['slide-1.jpg', 'slide-2.jpg', 'slide-3.jpg', 'slide-4.jpg']
                // 通过document对象获取页面元素的常用方法有5个: 
                // document.getElementById('...') ==> 通过ID获取单个元素
                // document.getElementsByTagName('...') ==> 通过标签名获取元素的列表
                // document.getElementsByClassName('...') ==> 通过类名获取元素的列表
                // document.querySelector('...') ==> 通过样式表选择器获取单个元素
                // document.querySelectorAll('...') ==> 通过样式表选择器获取元素的列表
                var img = document.querySelector('img');
                // var img = document.getElementsByTagName('img')[0];
                var timerId;
                
                startIt();
                
                var div = document.querySelector('#adv');
                div.addEventListener('mouseover', stopIt);
                div.addEventListener('mouseout', startIt);
                
                function startIt() {
                    timerId = window.setInterval(function() {
                        index += 1;
                        index %= images.length;
                        img.src = 'img/' + images[index];
                    }, 2000);
                }
                
                function stopIt() {
                    window.clearInterval(timerId);
                }
            </script>
        </body>
    </html>
    

    六、时间冒泡和事件捕获

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
            <style>
                #one {
                    width: 400px;
                    height: 400px;
                    background-color: indianred;
                    margin: 60px auto;
                }
                #two {
                    width: 300px;
                    height: 300px;
                    background-color: darkseagreen;
                }
                #three {
                    width: 200px;
                    height: 200px;
                    background-color: lightsteelblue;
                }
                #two, #three {
                    position: relative;
                    left: 50px;
                    top: 50px;
                }
            </style>
        </head>
        <body>
            <div id="one">
                <div id="two">
                    <div id="three"></div>
                </div>
            </div>
            <script>
                var one = document.querySelector('#one');
                var two = document.querySelector('#two');
                var three = document.querySelector('#three');
                // addEventListener方法的第一个参数是事件名
                // 第二个参数是事件发生时需要执行的回调函数
                // 第三个参数是一个布尔值 
                // 如果是true表示事件捕获 - 从外层向内层传递事件
                // 如果是false表示事件冒泡 - 从内存向外层传递事件
                // 一般情况下事件处理的方式都是事件冒泡(默认行为)
                // 如果想阻止事件的传播行为可以调用事件对象的stopPropagation方法
                one.addEventListener('click', function() {
                    window.alert('I am one!');
                });
                two.addEventListener('click', function() {
                    window.alert('I am two!');
                });
                // 事件回调函数中的第一个参数是事件对象(封装了和事件相关的信息)
                three.addEventListener('click', function(evt) {
                    window.alert('I am three!');
                    evt.stopPropagation();
                });
            </script>
        </body>
    </html>
    

    七、获取事件源和访问相关元素

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
            <style>
                #buttons>button {
                    border: none;
                    outline: none;
                    width: 120px;
                    height: 40px;
                    font: 22px/40px Arial;
                    background-color: red;
                    color: white;
                }
            </style>
        </head>
        <body>
            <div id="buttons">
                <button><input type="checkbox">苹果</button>
                <button><input type="checkbox">香蕉</button>
                <button><input type="checkbox">草莓</button>
                <button><input type="checkbox">蓝莓</button>
                <button><input type="checkbox">榴莲</button>
                <button><input type="checkbox">西瓜</button>
                <button><input type="checkbox">芒果</button>
                <button><input type="checkbox">柠檬</button>
            </div>
            <script>
                var buttons = document.querySelectorAll('#buttons>button');
                for (var i = 0; i < buttons.length; i += 1) {
                    buttons[i].firstChild.addEventListener('click', function(evt) {
                        var checkbox = evt.target || evt.srcElement;
                        if (checkbox.checked) {
                            checkbox.parentNode.style.backgroundColor = 'lightseagreen';
                        } else {
                            checkbox.parentNode.style.backgroundColor = 'red';
                        }
                        evt.stopPropagation();
                    });
                    buttons[i].addEventListener('click', function(evt) {
                        // 通过事件对象的target属性可以获取事件源(谁引发了事件)
                        // 但是有的浏览器是通过srcElement属性获取事件源的
                        // 可以通过短路或运算来解决这个兼容性问题
                        var button = evt.target || evt.srcElement;
                        // 当获取到一个元素之后可以通过它的属性来获取它的父元素、子元素以及兄弟元素
                        // parentNode - 父元素
                        // firstChild / lastChild / children - 第一个子元素 / 最后一个子元素 / 所有子元素
                        // previousSibling / nextSibling - 前一个兄弟元素 / 后一个兄弟元素
                        var checkbox = button.firstChild;
                        checkbox.checked = !checkbox.checked;
                        if (checkbox.checked) {
                            button.style.backgroundColor = 'lightseagreen';
                        } else {
                            button.style.backgroundColor = 'red';
                        }
                    });
                }
            </script>
        </body>
    </html>
    

    八、动态添加和删除元素

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                * {
                    margin: 0;
                    padding: 0;
                }
                #container {
                    margin: 20px 50px;
                }
                #fruits li {
                    list-style: none;
                    width: 200px;
                    height: 50px;
                    font-size: 20px;
                    line-height: 50px;
                    background-color: cadetblue;
                    color: white;
                    text-align: center;
                    margin: 2px 0;
                }
                #fruits>li>a {
                    float: right;
                    text-decoration: none;
                    color: white;
                    position: relative;
                    right: 5px;
                }
                #fruits~input {
                    border: none;
                    outline: none;
                    font-size: 18px;
                }
                #fruits~input[type=text] {
                    border-bottom: 1px solid darkgray;
                    width: 200px;
                    height: 50px;
                    text-align: center;
                }
                #fruits~input[type=button] {
                    width: 80px;
                    height: 30px;
                    background-color: coral;
                    color: white;
                    vertical-align: bottom;
                    cursor: pointer;
                }
            </style>
        </head>
        <body>
            <!-- <a href="mailto:957658@qq.com">联系站长</a> -->
            <div id="container">
                <ul id="fruits">
                    <!-- a标签有默认的跳转页面的行为有两种方法可以阻止它的默认行为-->
                    <li>苹果<a href="">×</a></li>
                    <li>香蕉<a href="">×</a></li>
                    <li>火龙果<a href="">×</a></li>
                    <li>西瓜<a href="">×</a></li>
                </ul>
                <input type="text" name="fruit">
                <input id="ok" type="button" value="确定">
            </div>
            <script src="js/mylib.js"></script>
            <script>
                function removeItem(evt) {
                    evt.preventDefault();
                    var a = evt.target || evt.srcElement;
                    var li = a.parentNode;
                    li.parentNode.removeChild(li);
                }
                
                function addItem() {
                    var fruitName = input.value.trim();
                    if (fruitName.length > 0) {
                        var li = document.createElement('li');
                        li.textContent = fruitName;
                        li.style.backgroundColor = randomColor();
                        var a = document.createElement('a');
                        a.href = '';
                        a.textContent = '×';
                        a.addEventListener('click', removeItem);
                        li.appendChild(a);
                        ul.insertBefore(li, ul.firstChild);
                    }
                    input.value = '';
                    input.focus();
                }
                
                var anchors = document.querySelectorAll('#fruits a');
                for (var i = 0; i < anchors.length; i += 1) {
                    anchors[i].addEventListener('click', removeItem);
                }
                
                var ul = document.getElementById('fruits');
                var input = document.querySelector('#container input[type=text]');
                input.addEventListener('keypress', function(evt) {
                    var key = evt.keyCode || evt.which;
                    if (key == 13) {
                        addItem();
                    }
                });
                var okButton = document.querySelector('#ok');
                okButton.addEventListener('click', addItem);
            </script>
        </body>
    </html>
    

    九、流氓浮动广告

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                * {
                    margin: 0;
                    padding: 0;
                }
                #container {
                    margin: 20px 50px;
                }
                #fruits li {
                    list-style: none;
                    width: 200px;
                    height: 50px;
                    font-size: 20px;
                    line-height: 50px;
                    background-color: cadetblue;
                    color: white;
                    text-align: center;
                    margin: 2px 0;
                }
                #fruits>li>a {
                    float: right;
                    text-decoration: none;
                    color: white;
                    position: relative;
                    right: 5px;
                }
                #fruits~input {
                    border: none;
                    outline: none;
                    font-size: 18px;
                }
                #fruits~input[type=text] {
                    border-bottom: 1px solid darkgray;
                    width: 200px;
                    height: 50px;
                    text-align: center;
                }
                #fruits~input[type=button] {
                    width: 80px;
                    height: 30px;
                    background-color: coral;
                    color: white;
                    vertical-align: bottom;
                    cursor: pointer;
                }
            </style>
        </head>
        <body>
            <!-- <a href="mailto:957658@qq.com">联系站长</a> -->
            <div id="container">
                <ul id="fruits">
                    <!-- a标签有默认的跳转页面的行为有两种方法可以阻止它的默认行为-->
                    <li>苹果<a href="">×</a></li>
                    <li>香蕉<a href="">×</a></li>
                    <li>火龙果<a href="">×</a></li>
                    <li>西瓜<a href="">×</a></li>
                </ul>
                <input type="text" name="fruit">
                <input id="ok" type="button" value="确定">
            </div>
            <script src="js/mylib.js"></script>
            <script>
                function removeItem(evt) {
                    evt.preventDefault();
                    var a = evt.target || evt.srcElement;
                    var li = a.parentNode;
                    li.parentNode.removeChild(li);
                }
                
                function addItem() {
                    var fruitName = input.value.trim();
                    if (fruitName.length > 0) {
                        var li = document.createElement('li');
                        li.textContent = fruitName;
                        li.style.backgroundColor = randomColor();
                        var a = document.createElement('a');
                        a.href = '';
                        a.textContent = '×';
                        a.addEventListener('click', removeItem);
                        li.appendChild(a);
                        ul.insertBefore(li, ul.firstChild);
                    }
                    input.value = '';
                    input.focus();
                }
                
                var anchors = document.querySelectorAll('#fruits a');
                for (var i = 0; i < anchors.length; i += 1) {
                    anchors[i].addEventListener('click', removeItem);
                }
                
                var ul = document.getElementById('fruits');
                var input = document.querySelector('#container input[type=text]');
                input.addEventListener('keypress', function(evt) {
                    var key = evt.keyCode || evt.which;
                    if (key == 13) {
                        addItem();
                    }
                });
                var okButton = document.querySelector('#ok');
                okButton.addEventListener('click', addItem);
            </script>
        </body>
    </html>
    

    十、jQuery实现表格效果

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
            <style>
                #data {
                    border-collapse: collapse;
                }
                #data td, #data th {
                    width: 120px;
                    height: 40px;
                    text-align: center;
                    border: 1px solid black;
                }
                #buttons {
                    margin: 10px 0;
                }
            </style>
        </head>
        <body>
            <table id="data">
                <caption>数据统计表</caption>
                <tbody>
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>身高</th>
                    <th>体重</th>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                </tbody>
            </table>
            <div id="buttons">
                <button id="pretty">隔行换色</button>
                <button id="clear">清除数据</button>
                <button id="remove">删单元格</button>
                <button id="hide">隐藏表格</button>
            </div>
            <!-- jQuery: Write Less Do More -->
            <!-- 加载本地的jQuery文件适合开发和测试时使用 -->
            <script src="js/jquery.min.js"></script>
            <!-- 下面的方式适合商业项目通过CDN服务器来加速获取jQuery的JS文件 -->
            <!-- <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> -->
            <script>
                // JavaScript Object Notation == JSON
                var stu = {
                    'id': 1001,
                    'name': '骆昊',
                    'age': 15,
                    'study': function(course) {
                        alert(this.name + '正在学习' + course);
                    },
                    'watchAv': function() {
                        if (this.age >= 18) {
                            alert(this.name + '正在观看岛国动作片');
                        } else {
                            alert(this.name + '只能观看《熊出没》');
                        }
                    }
                };
                stu.study('Python');
                stu.watchAv();
                
                $(function() {
                    $('#hide').on('click', function() {
                        // 根据样式表选择器获取元素 获取到的不是原生的JS对象
                        // 而是经过jQuery封装过后的对象(有更多的方法方便操作)
                        $('#data').fadeOut(2000);
                    });
                    $('#remove').on('click', function() {
                        $('#data tr:gt(0):last-child').remove();
                    });
                    $('#clear').on('click', function() {
                        $('#data tr:gt(0)>td').empty();
                    });
                    $('#pretty').on('click', function() {
                        $('#data tr:gt(0):odd').css({
                            'background-color': '#ccc',
                            'font-size': '36px',
                            'font-weight': 'bolder'
                        });
                        $('#data tr:gt(0):even').css('background-color', '#abc');
                    });
                });
            </script>
        </body>
    </html>
    

    十一、jQuery实现动态列表

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                * {
                    margin: 0;
                    padding: 0;
                }
                #container {
                    margin: 20px 50px;
                }
                #fruits li {
                    list-style: none;
                    width: 200px;
                    height: 50px;
                    font-size: 20px;
                    line-height: 50px;
                    background-color: cadetblue;
                    color: white;
                    text-align: center;
                    margin: 2px 0;
                }
                #fruits>li>a {
                    float: right;
                    text-decoration: none;
                    color: white;
                    position: relative;
                    right: 5px;
                }
                #fruits~input {
                    border: none;
                    outline: none;
                    font-size: 18px;
                }
                #fruits~input[type=text] {
                    border-bottom: 1px solid darkgray;
                    width: 200px;
                    height: 50px;
                    text-align: center;
                }
                #fruits~input[type=button] {
                    width: 80px;
                    height: 30px;
                    background-color: coral;
                    color: white;
                    vertical-align: bottom;
                    cursor: pointer;
                }
            </style>
        </head>
        <body>
            <div id="container">
                <ul id="fruits">
                    <li>苹果<a href="">×</a></li>
                    <li>香蕉<a href="">×</a></li>
                    <li>火龙果<a href="">×</a></li>
                    <li>西瓜<a href="">×</a></li>
                </ul>
                <input id='name' type="text" name="fruit">
                <input id="ok" type="button" value="确定">
            </div>
            <script src="js/jquery.min.js"></script>
            <script>
                function removeItem(evt) {
                    evt.preventDefault();
                    // $函数的第四种用法:参数是原生的JS对象
                    // 将原生的JS对象包装成对应的jQuery对象
                    $(evt.target).parent().remove();
                }
                
                // $函数的第一种用法: 参数是另一个函数
                // 传入的函数是页面加载完成之后要执行的回调函数
                // $(document).ready(function() {});
                $(function() {
                    // $函数的第二种用法:参数是一个选择器字符串
                    // 获取元素并得到与之对应的jQuery对象(伪数组)
                    $('#fruits a').on('click', removeItem);
                    $('#ok').on('click', function() {
                        var fruitName = $('#name').val().trim();
                        if (fruitName.length > 0) {
                            $('#fruits').append(
                                // $函数的第三种用法:参数是一个标签字符串
                                // 创建新元素并得到与之对应的jQuery对象
                                $('<li>').text(fruitName).append(
                                    $('<a>').attr('href', '').text('×').on('click', removeItem)
                                )
                            );
                        }
                        // 对jQuery对象使用下标运算或调用get()方法会得到原生JS对象
                        $('#name').val('').get(0).focus();
                    });
                });
            </script>
        </body>
    </html>
    

    十二、Ajax加载美女图片(原生JavaScript)

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
        </head>
        <body>
            <button id="ok">换一组</button>
            <div id="container"></div>
            <!-- HTML: Hyper-Text Markup Language -->
            <!-- XML: eXtensible Markup Language -->
            <!-- XML最为重要的用途是在两个异构的系统之间交换数据 -->
            <!-- 现在这项功能基本上被JSON和YAML格式替代了 -->
            <!-- Ajax: Asynchronous JavaScript and XML -->
            <!-- 通过JavaScript代码向服务器发起异步请求并获得数据 -->
            <!-- 异步请求:在不中断用户体验的前提下向服务器发出请求 -->
            <!-- 获得数据后可以通过DOM操作对页面进行局部刷新加载服务器返回的数据 -->
            <script>
                (function() {
                    var div = document.getElementById('container');
                    var button = document.getElementById('ok');
                    button.addEventListener('click', function() {
                        // 1. 创建异步请求对象
                        var xhr = new XMLHttpRequest();
                        if (xhr) {
                            var url = 'http://api.tianapi.com/meinv/?key=772a81a51ae5c780251b1f98ea431b84&num=10';
                            // 2. 配置异步请求
                            xhr.open('get', url, true);
                            // 3. 绑定事件回调函数(服务器成功响应后要干什么)
                            xhr.onreadystatechange = function() {
                                if (xhr.readyState == 4 && xhr.status == 200) {
                                    div.innerHTML = '';
                                    // 5. 解析服务器返回的JSON格式的数据
                                    var jsonObj = JSON.parse(xhr.responseText);
                                    var array = jsonObj.newslist;
                                    // 6. 通过DOM操作实现页面的局部刷新
                                    for (var i = 0; i < array.length; i += 1) {
                                        var img = document.createElement('img');
                                        img.src = array[i].picUrl;
                                        img.width = '250';
                                        div.appendChild(img);
                                    }
                                }
                            };
                            // 4. 发出请求
                            xhr.send();
                        } else {
                            alert('使用垃圾浏览器还想看美女,做梦!');
                        }
                    });
                })();
            </script>
        </body>
    </html>
    

    十三、Ajax加载美女图片(jQuery)

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
        </head>
        <body>
            <button id="ok">换一组</button>
            <div id="container"></div>
            <script src="js/jquery.min.js"></script>
            <script>
                $(function() {
                    $('#ok').on('click', function() {
                        var url = 'http://api.tianapi.com/meinv/?key=772a81a51ae5c780251b1f98ea431b84&num=10';
                        $.getJSON(url, function(jsonObj) {
                            $('#container').empty();
                            $.each(jsonObj.newslist, function(index, mm) {
                                $('#container').append(
                                    $('<img>').attr('width', '250').attr('src', mm.picUrl)
                                );
                            });
                        });
                    });
                });
            </script>
        </body>
    </html>
    

    作业一

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                * {
                    margin: 0;
                    padding: 0;
                }
                #adv {
                    width: 940px;
                    margin: 0 auto;
                }
                #adv ul {
                    width: 120px;
                    height: 30px;
                    margin: 0 auto;
                    position: relative;
                    top: -30px;
                }
                #adv li {
                    width: 30px;
                    height: 30px;
                    list-style: none;
                    float: left;
                    color: #ccc;
                    cursor: pointer;
                }
                #adv li:first-child {
                    color: lightseagreen;
                }
            </style>
        </head>
        <body>
            <div id="adv">
                <img src="img/slide-1.jpg" alt="">
                <ul>
                    <li class="dot">●</li>
                    <li class="dot">●</li>
                    <li class="dot">●</li>
                    <li class="dot">●</li>
                </ul>
            </div>
            <script>
                var img = document.querySelector('#adv>img');
                var items = document.querySelectorAll('#adv li');
                var timerId = 0;
                
                for (var i = 0; i < items.length; i += 1) {
                    items[i].index = i;
                    items[i].addEventListener('mouseover', function(evt) {
                        index = evt.target.index;
                        changeItemsColor(index);
                        img.src = 'img/' + images[index];
                        if (timerId != 0) {
                            window.clearInterval(timerId);
                            timerId = 0;
                        }
                    });
                    items[i].addEventListener('mouseout', startIt);
                }
                
                var images = ['slide-1.jpg', 'slide-2.jpg', 'slide-3.jpg', 'slide-4.jpg'];
                var index = 0;
                
                startIt();
                
                function startIt() {
                    if (timerId == 0) {
                        timerId = window.setInterval(function() {
                            index += 1;
                            index %= images.length;
                            changeItemsColor(index);
                            img.src = 'img/' + images[index];
                        }, 2000);
                    }
                }
                
                function changeItemsColor(index) {
                    for (var i = 0; i < items.length; i += 1) {
                        items[i].style.color = '#ccc';
                    }
                    items[index].style.color = 'lightseagreen';
                }
            </script>
        </body>
    </html>
    

    作业二

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                * {
                    margin: 0;
                    padding: 0;
                }
                #container {
                    margin: 10px 20px;
                }
                #container li {
                    float: left;
                    list-style: none;
                    width: 60px;
                    height: 60px;
                }
            </style>
        </head>
        <body>
            <div id="container">
                <img src="img/picture-1.jpg" alt="狗屎">
                <ul id="items">
                    <li><img src="img/thumb-1.jpg" alt=""></li>
                    <li><img src="img/thumb-2.jpg" alt=""></li>
                    <li><img src="img/thumb-3.jpg" alt=""></li>
                </ul>
            </div>
            <script>
                var img = document.querySelector('#container>img');
                var images = document.querySelectorAll('#items img');
                for (var i = 0; i < images.length; i += 1) {
                    // 事件回调函数在for循环的时候并没有执行所以也取不到循环变量i当前的值
                    // JavaScript是动态弱类型语言可以在运行时动态的添加(或删除)对象的属性
                    images[i].picture = 'img/picture-' + (i + 1) + '.jpg';
                    images[i].addEventListener('mouseover', function(evt) {
                        img.src = evt.target.picture;
                    });
                }
            </script>
        </body>
    </html>
    

    作业三

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                #container {
                    width: 800px;
                    height: 400px;
                    margin: 10px auto;
                    border: 1px solid black;
                    overflow: hidden;
                }
                #buttons {
                    width: 800px;
                    margin: 10px auto;
                    text-align: center;
                }
                #add, #fla {
                    border: none;
                    outline: none;
                    width: 80px;
                    height: 30px;
                    background-color: red;
                    color: white;
                    font-size: 16px;
                    cursor: pointer;
                }
                .small {
                    width: 80px;
                    height: 80px;
                    float: left;
                }
            </style>
        </head>
        <body>
            <div id="container"></div>
            <div id="buttons">
                <button id="add">添加</button>
                <button id="fla">闪烁</button>
            </div>
            <script src="js/mylib.js"></script>
            <script>
                var bigDiv = document.querySelector('#container');
                var addButton = document.querySelector('#add');
                addButton.addEventListener('click', function() {
                    var smallDiv = document.createElement('div');
                     smallDiv.className = 'small';
                    // smallDiv.style.width = '80px';
                    // smallDiv.style.height = '80px';
                    // smallDiv.style.float = 'left';
                    smallDiv.style.backgroundColor = randomColor();
                    bigDiv.insertBefore(smallDiv, bigDiv.firstChild);
                });
                var flaButton = document.querySelector('#fla');
                var isFlashing = false;
                var timerId;
                flaButton.addEventListener('click', function(evt) {
                    isFlashing = !isFlashing;
                    if (isFlashing) {
                        timerId = window.setInterval(function() {
                            var divs = document.querySelectorAll('#container>div');
                            for (var i = 0; i < divs.length; i += 1) {
                                divs[i].style.backgroundColor = randomColor();
                            }
                        }, 200);
                        flaButton.textContent = '暂停';
                    } else {
                        window.clearInterval(timerId);
                        flaButton.textContent = '闪烁';
                    }
                });
            </script>
        </body>
    </html>
    

    作业四

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                #data {
                    border-collapse: collapse;
                }
                #data td, #data th {
                    width: 120px;
                    height: 40px;
                    text-align: center;
                    border: 1px solid black;
                }
                #buttons {
                    margin: 10px 0;
                }
            </style>
        </head>
        <body>
            <table id="data">
                <caption>数据统计表</caption>
                <tbody>
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>身高</th>
                    <th>体重</th>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                <tr>
                    <td>Item1</td>
                    <td>Item2</td>
                    <td>Item3</td>
                    <td>Item4</td>
                    <td>Item5</td>
                </tr>
                </tbody>
            </table>
            <div id="buttons">
                <button id="pretty">隔行换色</button>
                <button id="clear">清除数据</button>
                <button id="remove">删单元格</button>
                <button id="hide">隐藏表格</button>
            </div>
            <script src="js/mylib.js"></script>
            <script>
                function prettify() {
                    var trs = document.querySelectorAll('#data tr');
                    for (var i = 1; i < trs.length; i += 1) {
                        trs[i].style.backgroundColor = 
                            i % 2 == 0 ? 'lightgray' : 'lightsteelblue';
                    }
                }
                
                function clear() {
                    var tds = document.querySelectorAll('#data td');
                    for (var i = 0; i < tds.length; i += 1) {
                        tds[i].textContent = '';
                    }
                }
                
                function removeLastRow() {
                    var table = document.getElementById('data');
                    if (table.rows.length > 1) {
                        table.deleteRow(table.rows.length - 1);
                    }
                }
                
                function hideTable() {
                    var table = document.getElementById('data');
                    table.style.visibility = 'hidden';
                }
                
                +function() {
                    var prettyBtn = document.querySelector('#pretty');
                    prettyBtn.addEventListener('click', prettify)
                    var clearBtn = document.querySelector('#clear');
                    clearBtn.addEventListener('click', clear);
                    var removeBtn = document.querySelector('#remove');
                    removeBtn.addEventListener('click', removeLastRow);
                    var hideBtn = document.querySelector('#hide');
                    hideBtn.addEventListener('click', hideTable);
                }();
            </script>
        </body>
    </html>
    

    作业五

    
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
            <style>
                * { 
                    margin: 0;
                    padding: 0;
                }
                body {
                    width: 960px;
                    margin: 20px auto;
                }
                #cart {
                    margin: 0 auto;
                    width: 850px;
                }
                #cart-header {
                    height: 40px;
                    background-color: lightgray;
                    margin-bottom: 20px;
                }
                #cart-header div {
                    line-height: 40px;
                }
                .left {
                    float: left;
                }
                .right {
                    float: right;
                }
                .w110 {
                    width: 100px;
                }
                .ml10 {
                    margin-left: 10px;
                }
                .w120 {
                    width: 120px;
                }
                .w250 {
                    width: 250px;
                }
                .center {
                    text-align: center;
                }
                .w20 {
                    width: 20px;
                }
                .w90 {
                    width: 90px;
                }
                .clear {
                    clear: both;
                }
                #cart-items>div {
                    height: 100px;
                }
                #cart-items>div>div {
                    line-height: 100px;
                }
                .w250 span {
                    display: inline-block;
                    font-size: 12px;
                    line-height: 16px !important;
                }
                .single-item {
                    border-bottom: 1px solid gray;
                }
                .small-button {
                    display: inline-block;
                    width: 20px;
                    height: 20px;
                    border: none;
                }
                .big-button {
                    color: white;
                    background-color: red;
                    display: inline-block;
                    width: 120px;
                    height: 40px;
                    border: none;
                    font-size: 22px;
                }
                #totalCount, #totalPrice {
                    color: red;
                }
                #totalPrice {
                    font: bolder 20px Arial;
                    display: inline-block;
                    width: 150px;
                }
                #cart a {
                    text-decoration: none;
                }
                #cart a:link, #cart a:visited, #cart a:active {
                    color: gray;
                }
            </style>
        </head>
        <body>
            <div id="cart">
                <div id="cart-header">
                    <div class="left w110 ml10">
                        <input id="selectAll" type="checkbox">
                        <label for="selectAll">全选</label>
                    </div>
                    <div class="left w250">商品</div>
                    <div class="left w120 center">单价</div>
                    <div class="left w120 center">数量</div>
                    <div class="left w120 center">小计</div>
                    <div class="left w120 center">操作</div>
                </div>
                <div id="cart-items">
                    <div class="clear single-item">
                        <div class="left w20 ml10">
                            <input name="selectOne" type="checkbox">
                        </div>
                        <div class="left w90">
                            <a href="">
                                <img src="img/a1.jpg">
                            </a>
                        </div>
                        <div class="left w250">
                            <span>
                            海澜之家/Heilan Home春装商务白衬衫男修身HNCAD3A067Y 漂白(69) 漂
                            </span>
                        </div>
                        <div class="left w120 center">&yen;<span class="price">138.00</span></div>
                        <div class="left w120 center">
                            <button class="small-button">-</button>
                            <input class="center count" type="text" size="2" value="1">
                            <button class="small-button">+</button>
                        </div>
                        <div class="left w120 center">&yen;<span>138.00</span></div>
                        <div class="left w120 center">
                            <a href="javascript:void(0);">删除</a>
                        </div>
                    </div>
                    <div class="clear single-item">
                        <div class="left w20 ml10">
                            <input name="selectOne" type="checkbox">
                        </div>
                        <div class="left w90">
                            <a href="">
                                <img src="img/a2.jpg">
                            </a>
                        </div>
                        <div class="left w250">
                            <span>
                            HLA海澜之家长袖衬衫男牛津纺休闲干净透气HNEAJ1E048A浅灰
                            </span>
                        </div>
                        <div class="left w120 center">&yen;<span class="price">128.00</span></div>
                        <div class="left w120 center">
                            <button class="small-button">-</button>
                            <input class="center count" type="text" size="2" value="1">
                            <button class="small-button">+</button>
                        </div>
                        <div class="left w120 center">&yen;<span>128.00</span></div>
                        <div class="left w120 center">
                            <a href="javascript:void(0);">删除</a>
                        </div>
                    </div>
                    <div class="clear single-item">
                        <div class="left w20 ml10">
                            <input name="selectOne" type="checkbox">
                        </div>
                        <div class="left w90">
                            <a href="">
                                <img src="img/a3.jpg">
                            </a>
                        </div>
                        <div class="left w250">
                            <span>
                            HLA海澜之家牛津纺清新休闲衬衫2018春季新品质感柔软长袖衬衫男
                            </span>
                        </div>
                        <div class="left w120 center">&yen;<span class="price">99.00</span></div>
                        <div class="left w120 center">
                            <button class="small-button">-</button>
                            <input class="center count" type="text" size="2" value="1">
                            <button class="small-button">+</button>
                        </div>
                        <div class="left w120 center">&yen;99.00</div>
                        <div class="left w120 center">
                            <a href="javascript:void(0);">删除</a>
                        </div>
                    </div>
                </div>
                <div id="cart-footer">
                    <div class="clear left">
                        <a id="clearSelected" href="javascript:void(0);">删除选中商品</a>
                    </div>
                    <div class="right">
                        <span>总共选中了<span id="totalCount">0</span>件商品</span>
                        <span>总计: <span id="totalPrice">&yen;0.00</span></span>
                        <button id="pay" class="big-button">去结算</button>
                    </div>
                </div>
            </div>
                <script src="js/jquery.min.js"></script>
            <script>
                function calcTotal() {
                    var amountsInput = $('.single-item input[type=text]');
                    var pricesSpan = $('.single-item .price');
                    var checkboxes = $('.single-item input[type=checkbox]');
                    var totalAmount = 0;
                    var totalPrice = 0;
                    amountsInput.each(function(index) {
                        if (checkboxes[index].checked) {
                            var amount = parseInt($(this).val());
                            totalAmount += amount;
                            var price = parseFloat($(pricesSpan[index]).text());
                            var currentPrice = (price * amount).toFixed(2);
                            $(this).parent().next().find('span').text(currentPrice);
                            totalPrice += parseFloat(currentPrice);
                        }
                    });
                    $('#totalCount').text(totalAmount);
                    $('#totalPrice').text('¥' + totalPrice.toFixed(2));
                }
                
                $(function() {              
                    $('#selectAll').on('click', function(evt) {
                        $('.single-item input[type=checkbox]').prop('checked', evt.target.checked);
                        calcTotal();
                    });
                    
                    $('.single-item button').on('click', function(evt) {
                        var op = $(evt.target).text();
                        if (op == '-') {
                            var numInput = $(evt.target).next();
                            var num = parseInt(numInput.val());
                            if (num > 1) {
                                numInput.val(num - 1);
                            }
                        } else {
                            var numInput = $(evt.target).prev();
                            var num = parseInt(numInput.val());
                            if (num < 200) {
                                numInput.val(num + 1);
                            }
                        }
                        $(evt.target).parent().parent().find('input[type=checkbox]').prop('checked', true);
                        calcTotal();
                    });
                    
                    $('.single-item input[type=checkbox]').on('click', function() {
                        calcTotal();
                    });
                    
                    $('.single-item a').on('click', function(evt) {
                        if (confirm('确定要删除该商品吗?')) {
                            $(evt.target).parent().parent().remove();
                            calcTotal();
                        }
                    });
                    
                    $('#clearSelected').on('click', function() {
                        if (confirm('确定要删除选中的商品吗?')) {
                            $('.single-item').each(function() {
                                if ($(this).find('input:checkbox').prop('checked')) {
                                    $(this).remove();
                                }
                            });
                            calcTotal();
                        }
                    });
                });
            </script>
        </body>
    </html>
    

    作业六

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
            <style>
                #one, #two, #three {
                    width: 200px;
                    height: 200px;
                    position: fixed;
                }
                #one {
                    left: 50px;
                    top: 50px;
                    background-color: lightpink;
                }
                #two {
                    left: 200px;
                    top: 150px;
                    background-color: lightgreen;
                }
                #three {
                    right: 30px;
                    top: 100px;
                    background-color: lightgoldenrodyellow;
                }
            </style>
        </head>
        <body>
            <div id="one"></div>
            <div id="two"></div>
            <div id="three"></div>
            <script src="js/jquery.min.js"></script>
            <script>
                $(function() {
                    makeDraggable($('#one'));
                    makeDraggable($('#two'));
                    makeDraggable($('#three'));
                });
                
                var draggables = [];
                
                function makeDraggable(jqElem) {
                    draggables.push(jqElem);
                    jqElem.on('mousedown', function(evt) {
                        this.isMouseDown = true;
                        this.oldX = evt.clientX;
                        this.oldY = evt.clientY;
                        this.oldLeft = parseInt($(evt.target).css('left'));
                        this.oldTop = parseInt($(evt.target).css('top'));
                        $.each(draggables, function(index, elem) {
                            elem.css('z-index', '0');
                        });
                        $(evt.target).css('z-index', '99');
                    })
                    .on('mousemove', function(evt) {
                        if (this.isMouseDown) {
                            var dx = evt.clientX - this.oldX;
                            var dy = evt.clientY - this.oldY;
                            $(evt.target).css('left', this.oldLeft + dx + 'px');
                            $(evt.target).css('top', this.oldTop + dy + 'px');
                        }
                    })
                    .on('mouseup', function(evt) {
                        this.isMouseDown = false;
                    })
                    .on('mouseout', function(evt) {
                        this.isMouseDown = false;
                    });
                }
            </script>
        </body>
    </html>
    

    相关文章

      网友评论

          本文标题:第二周总结

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