1. 程式人生 > >前端學習第71天JQ高階

前端學習第71天JQ高階

一,jq選擇器

- css3語法選擇器

```js
$('css3選擇器位')
```

- 索引匹配

```js
$('div:eq(0)')
$('div').eq(0)
```

- 內容

```js
$('div:contains(標籤文字內容)')
// 注: 採用模糊匹配
```
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>jq選擇器</title>
    <script src="js/jquery-3.3.1.js"
></script> </head> <body> <ul class="ul1"> <li class="li l1">ul1 l1</li> <li class="li l2">ul1 l2</li> <li class="li l3">ul1 l2</li> </ul> <ul class="ul2"> <li class="li l1">ul2 l1</li> <li class="li l2"
>ul2 l2</li> <li class="li l3">ul2 l3</li> </ul> </body> <script> // console.log($); // 1.採用css3語法 // $('css3選擇器') console.log($('.ul1 .l2').text()); console.log($('.l1 ~ .l2').text()); console.log($('.l1, .l2, .l3').text()); // 2.css3之前jq已有的自身選擇器
// 偶數位 // 注: 不加結構時, 將所有li作為考慮整體從上之下進行排序, 查詢索引為偶數位的(0,2...) console.log($('.ul1 .li:even')); // 奇數位 console.log($('.ul2 .li:odd')); // 匹配索引 ***** console.log($("ul").eq(0)); // $("ul")頁面中的所有ul, 取第n個ul // -- $("ul")[n] => 得到第n索引位js物件, 本非jq物件 // -- $("ul").eq(n) => 得到第n索引位jq物件 // -- $("ul:eq(n))" => 得到第n索引位jq物件 // 3.通過內容進行匹配 // 內容只有包含l1即可, ul1 l1 | ul1 l2 | ul1 l3 | ul2 l1 console.log($('li:contains(l1)').text()) </script> </html>

二, 屬性操作

1. 文字

```js
// 賦值: 有引數
$('.box').html('<i>beat box</i>');
// 取值: 無引數
console.log($('.box').text());
// 表單內容
// $('.inp').val("input 內容 為 value");
console.log($('.inp').val());
```

2.屬性

```js
// 取
console.log($('img').attr('alt'));
// 設
$('img').attr('src', 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1611571505,2177664062&fm=26&gp=0.jpg')
// 增
$('img').attr('abc', function () {
    return "ABC";
})
```

3.類名

```js
$(this).addClass('active'); // 新增
$(this).removeClass('box');  // 刪除
// 如果有active 刪除, 反之新增
$(this).toggleClass('active');  // 切換
```
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>屬性操作</title>
    <script src="js/jquery-3.3.1.js"></script>
    <style>
        .active {
            width: 100px;
            height: 100px;
            background-color: orange;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <input class="inp" type="text" value="12345">

    <img src="" alt="提示">
    <!--表單元素的布林型別屬性, 不寫為false, 書寫後,不管值為什麼, 均為屬性名-->
    <!--eg: checked="checked" | checked="" | checked-->
    <input class="ck" type="checkbox" checked="false">
</body>
<script>
    // 文字內容操作
    // html() | text() | val()

    // 賦值: 有引數
    $('.box').html('<i>beat box</i>');
    // 取值: 無引數
    console.log($('.box').text());
    // 表單內容
    // $('.inp').val("input 內容 為 value");
    console.log($('.inp').val());
</script>
<script>
    // 屬性操作
    console.log($('img').attr('alt'));
    $('img').attr('src', 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1611571505,2177664062&fm=26&gp=0.jpg')
    $('img').attr('abc', function () {
        return "ABC";
    })

    // $('.ck').prop("checked", "true");  // 瞭解
    // $('.ck').attr("checked", "true");
</script>
<script>
    $('.box').click(function () {
        // $(this).addClass('active'); // 新增
        // $(this).removeClass('box');  // 刪除

        // 如果有active 刪除, 反之新增
        $(this).toggleClass('active');  // 切換
    })
</script>
</html>

三.css樣式設定

```js
// 取值
console.log($('.box').css('font-size'));

// 設值
$('.box').css('color', 'deeppink')  // 單一屬性設值
    .css({  // 設定多個屬性值
        // 1.就是給css()函式賦值一個js物件
        // 2.key為字串型別,可以省略"",前提要使用js語法,小駝峰命名法
        // 2.屬性值為數值+單位方式,可以省略單位, 儘量全部用字串資料賦值
        width: '300px',
        'height': 300,
        'background-color': 'cyan',
        borderRadius: '30px'
    })
    .css('width', function(index, oldWidth) {  // 邏輯單一屬性設值
        if (index == 0) {
            // 延遲1s
            // var b_time = new Date().getTime();
            // while (new Date().getTime() - b_time < 1000){}
            return 1.5 * parseInt(oldWidth);
        }
        return oldWidth;
    })
```
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>樣式操作</title>
    <script src="js/jquery-3.3.1.js"></script>
    <style>
        .box {
            font-size: 100px;
        }
    </style>
</head>
<body>
    <div class="box">12345</div>
    <div class="box">67890</div>
</body>
<script>
    // 取值
    console.log($('.box').css('font-size'));

    // 設值
    $('.box').css('color', 'deeppink')
        .css({
            // 1.就是給css()函式賦值一個js物件
            // 2.key為字串型別,可以省略"",前提要使用js語法,小駝峰命名法
            // 2.屬性值為數值+單位方式,可以省略單位, 儘量全部用字串資料賦值
            width: '300px',
            'height': 300,
            'background-color': 'cyan',
            borderRadius: '30px'
        })
        .css('width', function(index, oldWidth) {
            if (index == 0) {
                // 延遲1s
                // var b_time = new Date().getTime();
                // while (new Date().getTime() - b_time < 1000){}
                return 1.5 * parseInt(oldWidth);
            }
            return oldWidth;
        })

四.JQ事件

- 繫結方式

```js
// 第一種 on
// 四個引數: 事件名, 委派的子級, {key-value傳入的資料}, 事件回撥函式
$('.box').on('click', 'span', {name: 'hehe'}, function(ev){})

// 第二種
// 兩個引數: {key-value傳入的資料}, 事件回撥函式
$('.box').click({name: 'hehe'}, function(ev){})
```

- 事件物件

```js
// 為jq事件物件, 相容js事件物件
// 座標: ev.clientX | ev.clientY
// 按鍵: ev.keyCode
// 資料: ev.data.key名  =>  eg:ev.data.name
```

- 冒泡與預設動作

```js
// 冒泡: ev.stopPropagation();
// 預設動作: ev.preventDefault();
```

- 委派

```js
$('.box').on('click', 'span', {name: 'hehe'}, function(ev){})
// 注: 通過父級box來繫結點選事件,其實將事件委派給其子級span標籤
```
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>jq事件</title>
    <style>
        .box, .ele, .sub {
            width: 100px;
            height: 100px;
            background-color: orange;
        }
        .sup {
            width: 200px;
            height: 200px;
            background-color: red;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="box">box</div>

    <a href="https://www.baidu.com">別動</a>

    <div class="ele">ele</div>

    <div class="sup">
        <div class="sub"></div>
        <span>123</span>
    </div>
</body>
<script src="js/jquery-3.3.1.js"></script>
<script>
    /*
    // 1.事件的繫結語法
    $('.box').on('click', function () {
        console.log('你丫點我了!!!')
    });
    $('.box').click(function () {
        console.log('你丫又點我了!!!')
    });
    
    // 2.事件物件
    $(document).click(function (ev) {
        console.log("父級點選了");
        // jq事件物件, 相容js事件物件
        console.log(ev);
        // 滑鼠點
        console.log(ev.clientX, ev.clientY);
    });
    $(document).keydown(function (ev) {
        // jq事件物件, 相容js事件物件
        console.log(ev);
        // 滑鼠點
        console.log(ev.keyCode);
    });

    // 3.冒泡與預設動作
    $('a').click(function (ev) {
        console.log("預設動作取消了");
        // 取消預設動作1
        ev.preventDefault();
        // 取消預設動作2
        // return false;
    })
    $('.ele').click(function (ev) {
        // ev.cancelBubble = true;  // 未相容
        // 阻止冒泡
        ev.stopPropagation();
        console.log("子級點選了");
    })
    */
</script>
<script>
    var name = "張三";

    /*
    $('.sub').click();
    $('.sub').on('click', {name: name, age: 8}, function (ev) {
        ev.stopPropagation();
        console.log(ev);
        console.log(">>>", ev.data.name)
    });
    */

    // 將sup的點選事件委派給自己的span子級
    $('.sup').on('click', 'span', {}, function (ev) {
        // ev.stopPropagation();
        console.log("==================");
    });
    $('.sup').on('click', {}, function (ev) {
        // ev.stopPropagation();
        console.log("++++++++++++++++");
    })

五.JQ動畫

- 系統預定義

```js
// time_num: 動畫持續的時間
// finish_fn: 動畫結束後的回撥函式

// 1. hide(time_num, finish_fn) | show(time_num, finish_fn) | toggle(time_num, finish_fn)
// 2. slideUp() | slideDown() | slideToggle()  引數同上
// 3.fadeOut() | fadeIn() | fadeTo() | fadeToggle()    引數同上
```

- 自定義動畫

```js
// 引數: 做動畫的樣式們 {}, 動畫持續時間, 運動曲線, 動畫結束後的回撥函式
animate({
    width: 300,
    height: 500
}, 300, 'linear', function() {
    // 動畫結束後回撥
})
// 動畫本體採用的是css動畫
```
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>jq動畫</title>
    <style>
        .ele {
            width: 100px;
            height: 100px;
            background-color: orange;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<button class="b1">消失</button>
<button class="b2">顯示</button>
<button class="b3">切換</button>
<div class="ele e1"></div>
<hr>
<button class="b4">消失</button>
<button class="b5">顯示</button>
<button class="b6">切換</button>
<div class="ele e2"></div>
<hr>
<button class="b7">消失</button>
<button class="b8">顯示</button>
<button class="b9">切換</button>
<div class="ele e3"></div>
<div class="ele e4"></div>
<div class="ele e5"></div>
</body>
<script src="js/jquery-3.3.1.js"></script>
<script>
    $('.b1').click(function () {
        $('.e1').hide(500, function () {
            console.log("動畫結束了, 你可以再幹一些事")
        });
    });
    $('.b2').click(function () {
        $('.e1').show(500, function () {
            console.log("動畫結束了, 你可以再幹一些事")
        });
    })
    $('.b3').click(function () {
        $('.e1').toggle(500, function () {
            console.log("動畫結束了, 你可以再幹一些事")
        });
    })
</script>
<script>
    $('.b4').click(function () {
        $('.e2').slideUp(500, function () {
            console.log("動畫結束了, 你可以再幹一些事")
        });
    });
    $('.b5').click(function () {
        $('.e2').slideDown(500, function () {
            console.log("動畫結束了, 你可以再幹一些事")
        });
    })
    $('.b6').click(function () {
        $('.e2').slideToggle(500, function () {
            console.log("動畫結束了, 你可以再幹一些事")
        });
    })
</script>

<script>
    $('.b7').click(function () {
        $('.e3, .e4, .e5').fadeOut(500, function () {
            console.log("動畫結束了, 你可以再幹一些事")
        });
    });
    $('.b8').click(function () {
        $('.e2 ~ .ele').fadeIn(500, function () {
            console.log("動畫結束了, 你可以再幹一些事")
        });
    })
    $('.b9').click(function () {
        $('.e3, .e4, .e5').fadeToggle(500, function () {
            console.log("動畫結束了, 你可以再幹一些事")
        });
    })
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>自定義動畫</title>
    <style>
        .box {
            width: 300px;
            height: 300px;
            background-color: orange;
        }
    </style>
</head>
<body>
    <button class="btn">消失</button>
    <button class="btn">顯示</button>
    <div class="box"></div>
</body>
<script src="js/jquery-3.3.1.js"></script>
<script>
    $('.btn').eq(0).on('click', function () {
        $('.box').animate({
            width: 0
        }, 1000, 'linear', function () {
            console.log("動畫結束了!!!")
        })
    });
    $('.btn').eq(1).on('click', function () {
        $('.box').animate({
            width: 300
        }, 'slow', 'swing', function () {
            console.log("動畫結束了!!!")
        })
    })

</script>
</html>

六 JQ輪播圖和JQ動畫案例

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>輪播圖</title>
    <style >
        * {
            /*不允許選擇文字, 網頁文字不能負責*/
            user-select: none;
        }
        body, ul {
            margin: 0;
            padding: 0;
            list-style: none;
        }
        .scroll {
            width: 1226px;
            height: 460px;
            margin: 0 auto;
            background-color: orange;
            position: relative;
            cursor: pointer;
        }
        .scroll_view {
            width: 100%;
            height: 100%;
            position: relative;
        }
        .scroll_view li {
            background: red;
            width: 100%;
            height: 100%;
            font: normal 100px/460px 'STSong';
            text-align: center;
            position: absolute;
            top: 0;
            left: 0;
            opacity: 0;
        }
        .scroll_view li.active {
            opacity: 1;
            transition: .5s;
        }
        .left {
            position: absolute;
            top: 170px;
            left: 0;
            background-color: #eee;
            font-size: 100px;
        }
        .left:hover, .right:hover {
            cursor: pointer;
            background-color: #333;
        }
        .right {
            position: absolute;
            top: 170px;
            right: 0;
            background-color: #eee;
            font-size: 100px;
        }

        .scroll_tag {
            position: absolute;
            right: 10px;
            bottom: 10px;
        }
        .scroll_tag li {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: #333;
            border: 3px solid #ddd;
            float: left;
            margin: 0 10px;
        }
        .scroll_tag li.active {
            background-color: #ccc;
            border: 3px solid #333;
        }
    </style>
</head>
<body>
<div class="scroll">
    <ul class="scroll_view">
        <li class="active">1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    <ul class="scroll_toggle">
        <li class="left">&lt;</li>
        <li class="right">&gt;</li>
    </ul>
    <ul class="scroll_tag">
        <li class="active"></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</div>
</body>
<script src="js/jquery-3.3.1.js"></script>
<script>
// 頁面文件樹載入完畢回撥
$(function () {
    var page_index = 0;
    var length = $('.scroll_view li').length;
    var toggle_time = 1000;
    var timer = 0;

    // 無限輪播
    timer = setInterval(toggleRole, toggle_time, 1);

    // 懸浮停止,移走輪播
    $('.scroll').mouseenter(function () {  // 懸浮停止
        clearInterval(timer);
    }).mouseleave(function () {  // 移走輪播
        timer = setInterval(toggleRole, toggle_time, 1);
    });

    // 右輪播
    $('.right').click(function () {
        toggleRole(1);
    });
    // 左輪播
    $('.left').click(function () {
        toggleRole(-1);
    });
    // 切換依據
    function toggleRole(role_num) {
        page_index += role_num;
        // role_num:1向右切換, role_num:-1向左切換
        if (role_num > 0) {
            if (page_index >= length) { // 右切換臨界點
                page_index = 0;
            }
        } else {
            if (page_index < 0) { // 左切換臨界點
                page_index = length - 1;
            }
        }
        toggleState(page_index);
    }
    // 切換狀態
    function toggleState(index) {
        $('.scroll_view li').removeClass('active').eq(index).addClass('active');
        $('.scroll_tag li').removeClass('active').eq(index).addClass('active');
    }
})
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>jq動畫案例</title>
    <style>
        .wrap {
            width: 600px;
            height: 200px;
            border: 5px solid black;
            margin: 0 auto;
            position: relative;
            overflow: hidden;
            /*overflow: auto;*/
        }
        .btn {
            text-align: center;
            margin-top: 50px;
        }
        ul {
            margin: 0;
            padding: 0;
            list-style: none;
        }
        .scroll {
            width: 2000px;
            position: absolute;
        }
        .scroll li {
            width: 200px;
            height: 200px;
            font: 500 50px/200px 'STSong';
            text-align: center;
            background-color: yellow;
            float: left;
        }
        .scroll li:nth-child(2n) {
            background-color: pink;
        }
    </style>
</head>
<body>
    <div class="btn">
        <button class="btn1">&lt;</button>
        <button class="btn2">&gt;</button>
    </div>
    <div class="wrap">
        <ul class="scroll">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
            <li>8</li>
            <li>9</li>
            <li>10</li>
        </ul>
    </div>
</body>
<script src="js/jquery-3.3.1.js"></script>
<!--
<script>
    // 滾動條滾動(overflow)產生的距離
    // console.log($('.wrap').scrollLeft());

    // 和絕對定位匹配使用
    // console.log($('.scroll').position().left);

    // 和固定定位匹配使用
    // console.log($('.scroll').offset());

    // 滾動scroll的總長度
    var scroll_total = $('.scroll').width();
    // 顯示的總寬度,也就是一次性最大滾動的長度
    var wrap_width = $('.wrap').width();
    $('.btn1').click(function () {
        // 往左已滾動的長度, 是負值
        var scroll_left = $('.scroll').position().left;
        // 剩餘的可滾動的長度: 總長丟擲顯示的一個平面長度,再減去已經滾動到左側的長度
        // 注scroll_left是負值,使用用+運算
        var less_long = scroll_total - wrap_width + scroll_left;
        // 通過剩餘的可滾動長度計算出下一次能滾動的長度
        var next_scroll = less_long > wrap_width ? wrap_width : less_long;
        // 動畫: left為從當前已滾動的長度(scroll_left)再滾動(減去)下一次可滾動的長度
        $('.scroll').animate({
            left: scroll_left - next_scroll
        })
    });

    $('.btn2').click(function () {
        // 往左已滾動的長度, 是負值
        var scroll_left = $('.scroll').position().left;
        // 往右剩餘的可滾動的長度
        var less_long = -scroll_left;
        // 通過剩餘的可滾動長度計算出下一次能滾動的長度
        var next_scroll = less_long > wrap_width ? wrap_width : less_long;
        $('.scroll').animate({
            left: scroll_left + next_scroll
        })
    })
</script>
-->

<script>
    // 不能被點選
    var disable_click = false;

    $('.btn1').click(function () {
        if (!disable_click) { // 能被點選時
            disable_click = true; // 動畫過程中, 應該不能再被點選
            $('.wrap').animate({
                scrollLeft: $('.wrap').scrollLeft() + 600
            }, 300, function () {
                disable_click = false;  // 動畫結束後,可以重新被點選
            })
        }
    });
    $('.btn2').click(function () {
        if (!disable_click) {
            disable_click = true;
            $('.wrap').animate({
                scrollLeft: $('.wrap').scrollLeft() - 600
            }, 300, function () {
                disable_click = false;
            })
        }
    })
</script>