6 JQuery

JQuery

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id='app'>小马哥</div>
    <!-- 1.引包 -->
    <script src="./jquery-3.4.1.js"></script>
    <script>
        var oDiv = document.getElementById('app');
        console.log(oDiv);
        // js对象=>jQuery对象
        console.log($(oDiv));
        
        // console.log(jQuery);
        // jquery对象转换js对象
        console.log($('#app')[0]);
        console.log($('#app').get(0));
        
        
        
    </script>
</body>
</html>
01 我的第一个jQuery
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script src="./jquery-3.4.1.js"></script>
    <script>

        // 只执行一次,后面会覆盖掉前面的
        // window.onload = function() {
        //     alert(1);
        // }
        // window.onload = function () {
        //     alert(2);
        // }
        // 跟jQuery的入口函数
        $(document).ready(function() {
            alert(1);
        })
        
        // $ jQuery
        // jquery的入口函数的简写方式
        // 重点
        $(function() {
            alert(2);
        })
    </script>
</body>

</html>
02 入口函数
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id='box'>小马哥</div>
    <script src="./index.js"></script>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        // jQuery提供了一个解决多个库变量名冲突的方法
        jQuery.noConflict(); //将jQuery的$变量的控制权交给index.js

        console.log($);

        (function ($) {
            $(function () {
                $('#box').css('color', 'red');
            })
        })(jQuery);
    </script>

</body>

</html>
03 多个库之间的冲突问题
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div class='box'>
        <p id='p1'>alex</p>
        <ul>
            <li class='item1'>张三</li>
            <li class='item2'>李四</li>
            <li class='item3'>王五</li>
        </ul>
    </div>
    <script src='./jquery-3.4.1.js'></script>
    <script>
        // jQuery的选择器的作用: 选中当前的元素(返回一个jQuery对象)
        // id
        // class
        // 标签
        // 后代
        // 子代
        // + prev+next
        // ~
        // 组合
        console.log($('#p1'));
        console.log($('.box'));
        console.log($('.box #p1'))
        console.log($('.box li'))
        console.log($('.box>ul>li'))
        
        console.log($('.item1+li'));//获取紧挨着的item1这个li标签的下一个标签
        console.log($('.item1~li')); //除item1这个li标签之外的标签
        console.log($('p,ul,li'));
        
        
    </script>

</body>

</html>
04 基础和层次选择器
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #p1 {
            display: none;
        }
    </style>
</head>

<body>
    <div class='box'>
        <p id='p1'>alex1</p>
        <p id='p2'>alex2</p>
        <ul>
            <li class='item1'>
                <h3>张三</h3>
            </li>
            <li class='item2'>李四张三2</li>
            <li class='item3'>王五</li>
            <li id='empty'>
                <h4>hello world</h4>
            </li>
        </ul>
        <input type="text" class='user'>
        <input type="password" class='pwd'>
        <input type="radio" class='sex'><input type="submit" class='sex' value='登录'>
    </div>
    <script src='./jquery-3.4.1.js'></script>
    <script>
        // 过滤选择器
        // console.log($('ul li:first'));
        // console.log($('ul li:last'));
        // console.log($('ul li:not(.item2)'));
        // console.log($('ul li:even'));
        // console.log($('ul li:odd'));//序号为奇数的(li标签从0开始计数)
        // // 非常重要
        // console.log($('ul li:eq(0)').text()); // 等于 //张三
        // console.log($('ul li:eq(2)').text());
        // console.log($('ul li:gt(0)').text()); //大于
        // console.log($('ul li:lt(2)').text()); //小于

        // 
        console.log($('ul li:contains(张三)'));
        console.log($('ul li:empty'));
        console.log($('ul li:has(h4)').addClass('a'));
        console.log($('.box p:hidden'));
        console.log($('.box p:visible'));

        console.log($('input[type=text]'));
        console.log($('input[type=password]'));
        console.log($('input:text'));
        console.log($('input:radio'));
        // console.log($('input[type!=radio]'));
        console.log($('input[type=button]'));
        
        if ($('input[type=submit]').length > 0) {
            $('input[type=submit]').click(function () {
                alert(111);
            })
        }else{
            throw new Error('获取元素失败');
        }
    </script>

</body>

</html>
05 过滤选择器
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    
</head>

<body>
    <h3>小马哥</h3>
    <div class='box'>
        
    </div>

    <div class="wrap">
        <button>按钮</button>
    </div>

    <div class="clone">
        <ul>
            <li>小马哥</li>
        </ul>
    </div>

    <div class="replace">
        <p>
            hello
        </p>
        <p>world</p>
    </div>
    <script src='./jquery-3.4.1.js'></script>
    <script>
        $(function() {
            // 替换节点
            // $('.replace p').replaceWith('<i>hello</i>');
            // $('<i>hello</i>').replaceAll('p');
            
            //包裹
            // $('.replace p').wrap('<div class="box2"></div>')
            // 2删除包裹的父节点
            // $('.replace p').unwrap();
            
            // 取到当前p标签的子内容,用strong标签包括起来(作用:把所有段落内的每个字内容加粗)
            $('.replace p').wrapInner('<strong></strong>')
            var h3Tag = document.createElement('h3');//创建一个元素节点
            h3Tag.innerText = 'alex';
            var htmlStr = '<h3>hello world</h3>';

            // append() appendTo()  后置追加
            // $('.box').append(h3Tag);
            // 如果是网页中的元素,那么是一种移动现象
            htmlstr = '<h3>你好</h3>';
            $('.box').append($(htmlStr));//$('.box').append($('<h3>你好</h3>'));
            $('h3').css('color','red');
            // console.log($('<h4>老村长</h4>').appendTo('.box'));
            $('<h4>老村长</h4>').appendTo('.box').css('color','green').click(function() {
                console.log($(this).text());
            });
            // 前置追加
            $('.box').prepend('<a href="#">百度一下</a>');
            $('<a href="#">百度一下2</a>').prependTo('.box');

            $('h3').after('<h1>wusir</h1>');
            $('<h2>老男孩</h2>').insertAfter('h1');


            $('button').click(function() {
                // alert(1);
                // 既删除节点,又删除节点上的事件绑定
                // console.log($(this).remove());
                // var btnJq = $(this).remove()
                // 仅仅删除了节点,事件保留
                // var btnJq = $(this).detach()
                // $('.box').prepend(btnJq);
                // $(this).detach();

                // 清空 div.box
                // $('.box').empty();
                // console.log($('.box').text());
                console.log($('.box').html());
                // input  val()
                // 清空
                $('.box').html('');
                
            })


            // 克隆元素
            $('.clone ul li').click(function() {
                $(this).clone(true).appendTo('.clone ul');
            })
        })
    </script>

</body>

</html>
06 DOM操作
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #box{
            width: 200px;
            height: 200px;
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <div name = 'b' class='active'></div>
    <img src="" alt="">

    <script src="./jquery-3.4.1.js"></script>
    <script>
    // 动态添加获取属性
    $(function() {
        // 设置单个属性值
        // $('div').attr('id','box');
        // 设置多个值
        $('div').attr({id:'box',title:'盒子'});
        console.log($('div').attr('name'));
        console.log($('div').attr('class'));
        setTimeout(function() {
            $('img').attr({
                src:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1568985509549&di=0bb1a6ced3db2b6be69d27579691f4e1&imgtype=0&src=http%3A%2F%2Fwww.chinadaily.com.cn%2Fhqzx%2Fimages%2Fattachement%2Fjpg%2Fsite385%2F20120924%2F00221918200911ca40e52b.jpg",
                alt:'美女'
            })
        }, 2000);
        
    })
    
    </script>
</body>
</html>
07 属性操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
        .active{
            color: red;
        }
    </style>
</head>
<body>
     <ul>
         <li class="item">张三</li>
         <li class="item">李四</li>
         <li class="item">王五</li>
     </ul>
     <script type="text/javascript" src="./jquery-3.4.1.js"></script>
     <script type="text/javascript">
         $(function(){

             $('ul li').click(function(){
                 // this指的是当前点击的DOM对象 ,使用$(this)转化jquery对象
                 $(this).addClass('active').siblings('li').removeClass('active');
             })
         })
     </script>

</body>

</html>

    
08 切换选中效果
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background-color: red;
        }
        .active{
            background-color: green;
        }
    </style>
</head>
<body>
    <div class='box'></div>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        $(function() {
            // var isRed = true;
            $('.box').click(function() {
                /* if(isRed){
                     $(this).addClass('active');
                     isRed = false;
                }else{
                     $(this).removeClass('active');
                     isRed = true;
                } */
                // if(!$(this).hasClass('active')){
                //     $(this).addClass('active');
                // }else{
                //      $(this).removeClass('active');
                // }

      

                // $(this).addClass('active a b')

                //动态的切换class类名为active
               $(this).toggleClass('active');
               
            })
        })
    
    </script>
    
</body>
</html>
08 类操作-颜色切换
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="content">
        <ul>
            <li>
                <p>获取到了</p>
            </li>
        </ul>
        <input type="text" value='美女'>
        <select name="" id="single">
            <option>苹果</option>
            <option>香蕉</option>
        </select>

        <select name="" id="multiple" multiple>
            <option selected>苹果</option>
            <option>香蕉</option>
            <option selected>橘子</option>
        </select>
        <input type="checkbox" value='A'> A
        <input type="checkbox" value='B'> B
        <input type="radio" value='1'><input type="radio" value='0'></div>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        $(function () {
            // 1 获取html中的值 既获取文本又获取html
            console.log($('#content ul li').html());
            // 2 设置html中的值
            $('#content ul li').html(`<img src="./timg.jpg" alt="">
            <p>小马哥</p>
            <h3>美女和野兽</h3>`);
            // 3 仅仅获取文本的值
            console.log($('#content ul li').text());

            // 4获取文本输入框的值
            console.log($('input[type=text]').val());
            $('input[type=text]').val('帅哥');

            //5设置默认选择框
            $('#single').val('香蕉');
            $('#multiple').val(['香蕉','橘子']);
            // // 给input设置值 要使用value属性值的值 不能使用文本的值
            $('input').val(['B','0 ']);

        })
    </script>
</body>

</html>
09 值操作
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div class="box">
        <p>alex</p>
        <h3>小马哥</h3>
        <ul>
            <li>wusir</li>
            <li>A</li>
            <li>B</li>
            <li>A</li>
            <li>A</li>
        </ul>
    </div>
    <div class="box2"></div>
    <div class="box3"></div>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        $(function () {
            // 获取匹配元素的子元素(亲儿子)集合
            console.log($('.box').children());
            console.log($('.box').next()); //获取下一个兄弟 (.box2)
            // 获取老爹
            console.log($('ul li').parent());
            // 获取的祖先辈们
            console.log($('ul li').parents());
            console.log($('.box2').prev()); //获取上一个兄弟
            
            $('ul li').eq(2).css('color','red'); 
            $('ul li:2').css('color','red'); 

        })
    </script>
</body>

</html>
10 -筛选方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        button {
            background-color: #fff;
        }
    </style>
</head>

<body>
    <ul>
        <li>
            <button>按钮1</button>
        </li>
        <li>
            <button>按钮2</button>
        </li>
        <li>
            <button>按钮3</button>
        </li>
        <li>
            <button>按钮4</button>
        </li>
        <li>
            <button>按钮5</button>
        </li>
    </ul>
    <script src='./jquery-3.4.1.js'></script>
    <!-- siblings -->
    <script>
        $('button').click(function () {
            // $(this).css('background-color', 'red').siblings('button').css('background-color', '#fff');
            $(this).css('background-color', 'red').parent().siblings('li').children().css('background-color', '#fff');
        })
    </script>
</body>

</html>
siblings运用-切换颜色选中

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        body{
            padding: 60px;
        }

        .fixHeader {
            width: 100%;
            height: 60px;
            background-color: red;
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 1000;

        }

        p {
            width: 200px;
            height: 200px;
            background-color: yellow;
            border: 1px solid green;
            position: absolute;
            top: 200px;
            left: 100px;
        }
    </style>
</head>

<body style="height:2000px;">
    <div class='fixHeader'></div>
    <div class="box">
        <p>
            小马哥
        </p>
    </div>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        $(function () {
            console.log($('.box').css('color'));
            // 设置值
            // $('.box').css('color','red');
            // $('.box').css('fontSize',20);
            $('.box').css({
                color: 'red',
                fontSize: 20
            })
            // 获取当前窗口的相对偏移  获取出来是一个对象 里面保存着 top和left属性
            var offset = $('p').offset();
            console.log(offset);

            $(window).scroll(function () {

                var scrollTop = $(this).scrollTop();
                if (scrollTop > offset.top) {
                    // console.log('导航条该出现了')
                    $('.fixHeader').stop().fadeIn(400);
                }else{
                    $('.fixHeader').stop().fadeOut(400);
                }


            })


        })
    </script>

</body>

</html>
12 css方法(滑动-导航条该出现了)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background: red;
            border: 2px solid #000;
            padding: 50px;
        }
    </style>
</head>
<body>
    <div class="box">

    </div>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        
        $(function() {
            // console.log($('.box').css('width'));
            // width
            console.log($('.box').width());
            console.log($('.box').height());
            // $('.box').width(300);
            // width+padding
            console.log($('.box').innerWidth());
            console.log($('.box').innerHeight());
            // 包括 width+padding+border
            console.log($('.box').outerWidth());
            
            
        })
    
    </script>
    
</body>
</html>
13 盒子宽高设置
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id='box' style="width: 200px;height: 200px;background:red;">小马哥</div>
    <footer>
        王华的todolist.cn <button id="clear-all">clear-all</button>
    </footer>
    <script src="./jquery-3.4.1.js"></script>

    <script>
        // click dblclick(不常用) mousedown/mouseup mousemove移动事件(不常用)
        // mouseover()/mouseout()
        // mouseenter()/mouseleave()
        // focus() blur()
        // keydown() keyup()

        // ready() 文档加载事件 scroll() 监听窗口滚动事件

        /* function click(fn) {
            if(fn){
                fn('1');
            }
        }
        click(function(c) {
            
        }) */

        $(function (params) {
              $('#clear-all').click(function() {
                 alert(1)
                //  $(this).hide(1000,function() {
                //      alert($(this).text());
                //  });
             }) 

            // 想一个问题:单击和双击是否会冲突? 如何解决冲突问题? 之间的时间差 是300ms
            $('#box').dblclick(function() {
                 console.log('双击了');
             })
            $('#box').mousedown(function () {
                console.log('鼠标摁下了');
            });
            $('#box').mouseup(function () {
                console.log('鼠标抬起了');
            })
            $('#box').mousemove(function() {
                console.log('移动了');
                
            })
        })


    </script>

</body>

</html>
13 鼠标事件一
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 40px;
            background-color: bisque;
            position: relative;
        }

        .box .content {
            position: absolute;
            width: 200px;
            height: 200px;
            top: 40px;
            background-color: red;
            display: none;
        }
    </style>
</head>

<body>
    <div id='box' style="width: 200px;height: 200px;background:red;">
        <p style="background:green">小马哥</p>
    </div>

    <div class="box">
        <div class="content"></div>
    </div>
    <script src="./jquery-3.4.1.js"></script>

    <script>
        // click dblclick(不常用) mousedown/mouseup mousemove移动事件(不常用)
        // mouseover()/mouseout() 鼠标穿过被选元素或者当前被选元素的子元素
        // mouseenter()/mouseleave() ****** 鼠标只穿过被选元素 *****
        // focus() blur()
        // keydown() keyup()
        // ready() 文档加载事件 scroll() 监听窗口滚动事件
        $(function (params) {
            $('#box').mouseover(function () {
                console.log('鼠标穿过了');

            })
            $('#box').mouseout(function () {
                console.log('鼠标离开了');

            })

            /* $('.box').mouseover(function () {
                console.log(1111);
                
                $('.content').show();
            })
            $('.box').mouseout(function () {
                $('.content').hide();
            }) */
            $('.box').mouseenter(function () {
                console.log(1111);
                // 使用动画的时候 先要停止动画 再开启动画
                $('.content').stop().slideDown();
            })
            $('.box').mouseleave(function () {
                $('.content').stop().slideUp();
            })
        })
    </script>

</body>

</html>
15 鼠标事件二
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 40px;
            background-color: bisque;
            position: relative;
        }

        .box .content {
            position: absolute;
            width: 200px;
            height: 200px;
            top: 40px;
            background-color: red;
            display: none;
        }
    </style>
</head>

<body>
    <input type="text">
    <script src="./jquery-3.4.1.js"></script>

    <script>
        // click dblclick(不常用) mousedown/mouseup mousemove移动事件(不常用)
        // mouseover()/mouseout() 鼠标穿过被选元素或者当前被选元素的子元素
        // mouseenter()/mouseleave() ****** 鼠标只穿过被选元素 *****
        // focus() 聚焦 blur()失焦
        // keydown() keyup()
        // ready() 文档加载事件 scroll() 监听窗口滚动事件
        $(function () {
            //    $('input[type=text]').focus();
            // $('input[type=text]').focus(function () {
            //     console.log('获取焦点了')
            // })
            // $('input[type=text]').blur(function () {
            //     console.log('失去焦点了')
            // })

            // 使用户无法使用文本框
            $('input[type=text]').focus(function () {
                this.blur();
            })

            // keydown
            $(window).keydown(function (event) {
                console.log('键盘按下了');
                console.log(event.keyCode); //获取不同键的数字
                // 空格 32  enter 13 esc 27
                // 不同的按键做不同的事情

                switch (event.keyCode) {
                    case 32:
                        //摁下空格键
                        console.log('空格键触发了');
                        
                        break;
                    case 13:
                        //摁下回车键
                        console.log('回车键触发了');
                        break;
                    default:
                        console.log('撤掉触发了');
                        break;
                }


            })

        })
    </script>

</body>

</html>
16 鼠标事件三(不同案件做不同的事情)
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>

    </style>
</head>

<body>
    <form action="">
        <input type="text">
        <select name="" id="select">
            <option value="a">a</option>
            <option value="b">b</option>
        </select>
        
        <input type="submit">
    </form>
    <script src="./jquery-3.4.1.js"></script>

    <script>
        // change()
        // select()
        // submit()
        $(function () {
            // 仅仅适用于文本input textarea select 
            $('input[type=text]').change(function () {
                //   console.log('值发生变化了');
                var val = $(this).val(); //获取输入的值
                console.log(val);
                if (/^\d{4}$/.test(val)) {
                    console.log('输入正确');
                } else {
                    console.log('输入错误');
                    $(this).css('borderColor', 'red');
                }

            })

            $('#select').change(function () {
                console.log($(this).val());
            })

            $('form').submit(function (event) {
                //   
                // 阻止默认行为
                event.preventDefault();
                console.log(1111);
                
                var val = $('input[type=text]').val();
                var oVal = $('#select').val();
                console.log(val,oVal);

                // 与后端发生交互性的行为
                // 封装了ajax  与后端发生交互的技术
            })

        })
    </script>

</body>

</html>
17 表单事件
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 200px;
            border: 1px solid red;
        }

        h3 {
            background-color: bisque;
        }
    </style>
</head>

<body>
    <div class="box">
        <h3>冒泡</h3>
    </div>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        $('.box').click(function () {
            alert('父元素点击了');
            return false;
        })
        $('h3').click(function (event) {
            // 阻止冒泡
            event.stopPropagation();
            alert('子点击了');
        })
        $(document).click(function() {
            alert('文档被点击了');
        })
    </script>
</body>

</html>
18 事件冒泡
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;

        }

        .slideDownView {
            width: 100%;
            height: 400px;
            background-color: aqua;
            position: fixed;
            top: 0;
            left: 0;
            display: none;
        }

        .slideDownView ul li {
            display: inline-block;
            width: 100px;
            height: 40px;
            background-color: blueviolet;

            line-height: 40px;
            text-align: center;
        }

        .slideDownView ul li a {
            display: block;
            widows: 100px;
            height: 40px;
            color: #fff;
        }
    </style>
</head>

<body>
    <a href="#" class="changefu">换肤</a>
    <div class="slideDownView">
        <ul>
            <li><a href="#">热门</a></li>
            <li><a href="#">游戏</a></li>
            <li><a href="#">美女</a></li>
        </ul>
    </div>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        $(function () {
            $('.changefu').click(function (event) {
                
                event.preventDefault(); // 阻止a标签的默认 行为
                event.stopPropagation(); //阻止冒泡行为

                $('.slideDownView').stop().slideDown(500);

                $('.slideDownView ul li a').click(function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    $(this).css('color', 'red').parent().siblings('li').children().css('color',
                        '#fff')
                })
            })

            $('.slideDownView,ul').click(function() {
                return false;
            })

            $(document).click(function() {
                 $('.slideDownView').stop().slideUp(500);
            })

        })
    </script>

</body>

</html>
19 冒泡事件
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <ul>
        <li>博客内容1</li>
    </ul>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        $(function () {

            /* $('ul li').click(function() {
                alert($(this).text());
            }) */

            // 原理:利用冒泡的原理,把事件加到父级上 触发执行效果 
            // on('事件名','seletor',callback)

            $('ul').on('click','li',function() {
                alert($(this).text());
            })
            //将来做的事情

            setTimeout(function(){
                $('<li>博客内容2</li>').appendTo('ul');
            }, 5000);


        })
    </script>
</body>

</html>
20 事件代理
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button id='btn'>显示</button>
    <div class="box" style="width: 200px;height: 200px;background: red;">

    </div>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        $(function () {

            /*  $('.box').mouseenter(function () {
                 $(this).stop().css('background','green')
             })
             $('.box').mouseleave(function () {
                 $(this).stop().css('background','red')
             }) */
            $('.box').hover(function () {
                $(this).css('background', 'green')
            }, function () {
                $(this).css('background', 'red')
            })
            var isShow = true;

            $('#btn').click(function () {
                //  if(isShow){
                //        $('.box').stop().hide();
                //     //    $(this).text('隐藏');
                //        isShow = false;
                //  }else{
                //      $('.box').stop().show();
                //     //  $(this).text('显示');
                //      isShow = true;
                //  }

                $('.box').toggle();





            })




        })
    </script>
</body>

</html>
21 合成事件
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <button id='btn'>显示</button>
    <div class="box" style="width: 200px;height: 200px;background: red;">
        小马哥
    </div>
    <script src="./jquery-3.4.1.js"></script>

    <script>
        $(function () {

            $('#btn').click(function () {
                // $('.box').hide(400);
                // $('.box').show();

                // 隐藏  fadeIn() 显示
                // $('.box').fadeOut(400);
                // $('.box').slideUp(400);
                // $('.box').slideDown(400);
                // $('.box').fadeTo(400,0.3);
                
                // $('.box').toggle(400);
                // $('.box').fadeToggle(400);
                // $('.box').stop().slideToggle(400);
                // jquery插件 jquery-color

                // 它既能实现 上面jQuery的动画效果 又能实现自定义动画的效果
                $('.box').animate({
                    width:300,
                    height: 300,
                    // 颜色  需要jquery的颜色插件配合  百度搜索jquery-color
                    // background:'green'
                    "font-size": 40
                },1000,function() {
                    
                })


            })




        })
    </script>
</body>

</html>
22 动画效果
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id='weather'>
        <p class="cond_txt"></p>
    </div>
    <div>

    </div>
    <div>
        
    </div>
    <script src="./jquery-3.4.1.js"></script>
    <script>
        $(function () {
            // ajax技术: 在不重载页面的情况下,与页面进行局部更新
            // get() post()
            // window.onload() 

            // 第三方 接口 和风天气
            // https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976
            $.ajax({
                url:'https://free-api.heweather.net/s6/weather/now?location=beijing&key=6d3438f74fb8415caf0ef3b797acb8d0',
                method:'get',
                success:function(res){
                    var status=res.HeWeather6[0].status;
                    if(status==='ok'){
                         // JSON
                        var cond_txt = res.HeWeather6[0].now.cond_txt;
                        $('#weather .cond_txt').html(cond_txt);
                    }
                    
                }
            })


            /* 
            // 伪代码
            $.ajax({
                url:'https://free-api.heweather.net/s6/weather/now',
                method:'post',
                data:{
                    username:'zhangsan',
                    password:$('input[type=password]').val()
                },
                success:function(res){

                }
            })
            
            
            */
            
        })
    </script>

</body>

</html>
23 ajax的使用
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        a {
            display: inline-block;
        }

        .header {
            width: 100%;
            height: 40px;
            line-height: 40px;
            background-color: #000;
            opacity: 0.4;
            position: relative;

        }

        .weather_now {
            display: inline-block;
        }

        .weather_now a {
            text-decoration: none;
            color: #fff;
        }

        .weather_now img {
            width: 30px;
            vertical-align: middle;
        }

        .show_weather {
            display: none;
            position: absolute;
            background-color: antiquewhite;
            top: 40px;
        }

        .everyday_item {
            display: inline-block;
            padding: 20px;
        }
    </style>
</head>

<body>
    <div class="header">
        <div class="weather_now">
            <a href="javascript:;">
                <span class='city'></span>
                <img src="" alt="" class="weatherImg">
                <span class="temp"></span>
                <span class="cond_txt"></span>
                <span class="fl"></span>
            </a>
            <div class="show_weather">
                <div class="everyday_weather">
                    <div class="everyday_item">
                        <!-- <p class="everyday_title">今天(星期一)</p>
                        <img class="everyday_icon" src='./images/101.png' />
                        <p class="everyday_temp">31℃</p>
                        <p class="everyday_cond_txt">晴</p>
                        <p class="everyday_cond_wind">北风</p> -->
                    </div>
                    <div class="everyday_item">
                        <!-- <p class="everyday_title">今天(星期一)</p>
                        <img class="everyday_icon" src='./images/101.png' />
                        <p class="everyday_temp">31℃</p>
                        <p class="everyday_cond_txt">晴</p>
                        <p class="everyday_cond_wind">北风</p> -->
                    </div>
                    <div class="everyday_item">
                        <!-- <p class="everyday_title">今天(星期一)</p>
                        <img class="everyday_icon" src='./images/101.png' />
                        <p class="everyday_temp">31℃</p>
                        <p class="everyday_cond_txt">晴</p>
                        <p class="everyday_cond_wind">北风</p> -->
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="./jquery-3.4.1.js"></script>
    <script src="./moment.js"></script>
    <script>
        $(function () {
            // 鼠标悬浮的操作
            $('.weather_now').mouseenter(function () {
                $('.show_weather').stop().fadeIn();
                getForecastWeather(
                    'https://free-api.heweather.net/s6/weather/forecast?location=beijing&key=4693ff5ea653469f8bb0c29638035976'
                )
            })
            $('.weather_now').mouseleave(function () {
                $('.show_weather').stop().fadeOut();
            })

            // 轮训 请求实况和未来三天天气
            setInterval(function () {
                getForecastWeather(
                    'https://free-api.heweather.net/s6/weather/forecast?location=beijing&key=4693ff5ea653469f8bb0c29638035976'
                );
                getNowWeather(
                    'https://free-api.heweather.net/s6/weather/now?location=beijing&key=4693ff5ea653469f8bb0c29638035976'
                );
            }, 1000 * 60 * 60);
            // 设置全局为中文
            moment.locale('zh-cn', {
                months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
                monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
                weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
                weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
                weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
                longDateFormat: {
                    LT: 'HH:mm',
                    LTS: 'HH:mm:ss',
                    L: 'YYYY-MM-DD',
                    LL: 'YYYY年MM月DD日',
                    LLL: 'YYYY年MM月DD日Ah点mm分',
                    LLLL: 'YYYY年MM月DD日ddddAh点mm分',
                    l: 'YYYY-M-D',
                    ll: 'YYYY年M月D日',
                    lll: 'YYYY年M月D日 HH:mm',
                    llll: 'YYYY年M月D日dddd HH:mm'
                },
                meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
                meridiemHour: function (hour, meridiem) {
                    if (hour === 12) {
                        hour = 0;
                    }
                    if (meridiem === '凌晨' || meridiem === '早上' ||
                        meridiem === '上午') {
                        return hour;
                    } else if (meridiem === '下午' || meridiem === '晚上') {
                        return hour + 12;
                    } else {
                        // '中午'
                        return hour >= 11 ? hour : hour + 12;
                    }
                },
                meridiem: function (hour, minute, isLower) {
                    const hm = hour * 100 + minute;
                    if (hm < 600) {
                        return '凌晨';
                    } else if (hm < 900) {
                        return '早上';
                    } else if (hm < 1130) {
                        return '上午';
                    } else if (hm < 1230) {
                        return '中午';
                    } else if (hm < 1800) {
                        return '下午';
                    } else {
                        return '晚上';
                    }
                },
                calendar: {
                    sameDay: '[今天]LT',
                    nextDay: '[明天]LT',
                    nextWeek: '[下]ddddLT',
                    lastDay: '[昨天]LT',
                    lastWeek: '[上]ddddLT',
                    sameElse: 'L'
                },
                dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/,
                ordinal: function (number, period) {
                    switch (period) {
                        case 'd':
                        case 'D':
                        case 'DDD':
                            return number + '';
                        case 'M':
                            return number + '';
                        case 'w':
                        case 'W':
                            return number + '';
                        default:
                            return number;
                    }
                },
                relativeTime: {
                    future: '%s内',
                    past: '%s前',
                    s: '几秒',
                    ss: '%d秒',
                    m: '1分钟',
                    mm: '%d分钟',
                    h: '1小时',
                    hh: '%d小时',
                    d: '1天',
                    dd: '%d天',
                    M: '1个月',
                    MM: '%d个月',
                    y: '1年',
                    yy: '%d年'
                },
                week: {
                    dow: 1,
                    doy: 4
                }
            })
            // console.log(moment('2019-09-23').format('dddd'));

            // 获取今天,明天,后天
            function getDay(i) {
                switch (i) {
                    case 0:
                        return '今天'
                        break;
                    case 1:
                        return '明天'
                        break;
                    default:
                        return '后天'
                        break;
                }
            }
            // 获取未来三天的天气
            function getForecastWeather(url) {

                // 发送ajax请求未来三天的天气

                $.ajax({
                    url: url,
                    method: 'get',
                    success: function (res) {
                        // console.log(res);
                        var daily_forecast = res.HeWeather6[0].daily_forecast;
                        // each();
                        $('.everyday_item').each(function (i) {
                            var cond_code_d = daily_forecast[i].cond_code_d;
                            var tmp_max = daily_forecast[i].tmp_max;
                            var cond_txt_d = daily_forecast[i].cond_txt_d;
                            var wind_dir = daily_forecast[i].wind_dir;
                            var date = daily_forecast[i].date;
                            var week = moment(date).format('dddd');

                            $(this).empty();
                            $(this).append(`
                                <p class="everyday_title">${getDay(i)}(${week})</p>
                                <img class="everyday_icon" src='./images/${cond_code_d}.png' />
                                <p class="everyday_temp">${tmp_max}℃</p>
                                <p class="everyday_cond_txt">${cond_txt_d}</p>
                                <p class="everyday_cond_wind">${wind_dir}</p>
                            `)

                        })

                    },
                    error: function (err) {
                        console.log(err);

                    }
                })


            }

            // 获取现在的天气
            function getNowWeather(url) {
                // 发送ajax到和风天气服务器获取数据
                $.ajax({
                    url: url,
                    method: 'get',
                    success: function (res) {
                        var status = res.HeWeather6[0].status;
                        if (status === 'ok') {
                            var now = res.HeWeather6[0].now;
                            var city = res.HeWeather6[0].basic.location;
                            // 实况天气图标码
                            var cond_code = now.cond_code;
                            // 天气状况
                            var cond_txt = now.cond_txt;
                            // 当前温度
                            var tmp = now.tmp;
                            // 体感温度
                            var fl = now.fl;

                            $('.city').html(city + ':');
                            $('.weatherImg').attr('src',
                                `./images/${cond_code}.png`)
                            $('.temp').html(tmp + '');
                            $('.cond_txt').html(cond_txt);
                            $('.fl').html(fl);

                        }
                    },
                    error: function (err) {
                        console.log(err);
                    }
                })
            }
            getNowWeather(
                'https://free-api.heweather.net/s6/weather/now?location=beijing&key=6d3438f74fb8415caf0ef3b797acb8d0'
            );
        })
    </script>
</body>

</html>
24 案例-百度的天气

 

ToDolist案例

 

 

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>ToDoList—最简单的待办事项列表</title>
    <link rel="stylesheet" href="./css/index.css">
</head>

<body>
    <header>
        <section>
            <form action="javascript:;" id="form">
                <label for="title">ToDoList</label>
                <input type="text" id="title" name="title" placeholder="添加ToDo"/>
            </form>
        </section>
    </header>
    <section>
        <h2>正在进行 <span id="todocount"></span></h2>
        <ol id="todolist" class="demo-box">

        </ol>
        <h2>已经完成 <span id="donecount"></span></h2>
        <ul id="donelist">
            
        </ul>
    </section>
    <footer>
        王华的todolist.cn <button style="background-color: rgb(244,0,0.2);" id="clear-all">clear-all</button>
    </footer>
    <script src="./jquery-3.4.1.js"></script>
    <script type="text/javascript" src="./js/index.js"></script>
</body>

</html>
todoList.html
$(function () {


    // 加载数据的方法
    function loadData() {
        var collection = localStorage.getItem('todo');
        if(collection){
            return JSON.parse(collection);
        }else{
            return [];
        }
    }
    // 保存数据的方法
    function saveData(data) {
        localStorage.setItem('todo',JSON.stringify(data));
    }
    // 加载网页数据
    load();
    function load() {
        var todoCount = 0;
        var doneCount = 0;
        var doneStr = '';
        var todoStr = '';
        var todoList = loadData();
        if (todoList && todoList.length > 0) {
            // 有数据
            todoList.forEach(function (data, i) {
                if (data.done) {
                    // 已经完成
                    doneStr += `
                        <li>
                            <input type="checkbox" index=${i} checked='checked'>
                            <p id='p-${i}' index=${i}>${data.title}</p>
                            <a href="javascript:;">-</a>
                         </li>
                    `;
                    doneCount++;
                } else {
                    // 正在进行
                    todoStr += `
                        <li>
                            <input type="checkbox" index=${i}>
                            <p id='p-${i}' index=${i}>${data.title}</p>
                            <a href="javascript:;">-</a>
                         </li>
                    `;
                    todoCount++;
                }
                $('#todolist').html(todoStr);
                $('#donelist').html(doneStr);
                $('#todocount').html(todoCount);
                $('#donecount').html(doneCount);;

            })


        } else {
            // 无数据
            $('#todolist').html('');
            $('#donelist').html('');
            $('#todocount').html(todoCount);
            $('#donecount').html(doneCount);

        }
    }

    // 添加数据的方法
    $("#title").keydown(function(event) {
        if(event.keyCode === 13){
            // 获取输入框中的值
            var val = $(this).val();
            if(!val){
                alert('不能为空,请重新输入')
            }else{
                var data = loadData();
                data.unshift({
                    title: val,
                    done: false
                });
                // 清空input输入框中的值
                $(this).val('');
                saveData(data);
                load();

            }
        }
    })

    // 事件代理的方式 删除操作
    $('#todolist').on('click','a',function() {
        var todoList = loadData();
        var i = $(this).parent().index();
        todoList.splice(i,1);
        saveData(todoList)
        load();
    })

    // 更新数据
    $('#todolist').on('change','input[type=checkbox]',function() {
        var i = parseInt($(this).attr('index'));
        // 更新数据
        update(i,'done',true);
    })
    $('#donelist').on('change', 'input[type=checkbox]', function () {
        var i = parseInt($(this).attr('index'));
        // 更新数据
        update(i, 'done', false);
    })
    function update(i,key,value){
        var data = loadData();
        var todo = data.splice(i,1)[0];
        todo[key] = value;
        data.splice(i,0,todo);
        saveData(data);
        load();
    }

    // 编辑操作
    $('#todolist').on('click','p',function() {
        var i = parseInt($(this).attr('index'));
        var title = $(this).html();
        var $p = $(this);
        $p.html(`
            <input type="text" id='input-${i}' value=${title}>
        `)
        // 选中
        $(`#input-${i}`)[0].setSelectionRange(0, $(`#input-${i}`).val().length);
        // 获取焦点
        $(`#input-${i}`).focus();

        // 失去焦点保存更改的数据
        $(`#input-${i}`).blur(function() {
            if($(this).val().length === 0){
                $p.html(title);
                alert('内容不能为空');
            }else{
                update(i,'title',$(this).val())
            }
        })    
    })

    // 删除所有数据
    $("#clear-all").click(function () {
        var data = loadData();
        data.splice(0,data.length);
        saveData(data);
        load();
    });
    
  


})
index.js

 

posted @ 2021-06-14 17:17  风hua  阅读(64)  评论(0编辑  收藏  举报