1

jQuery 属性,元素

属性操作

固定属性 prop()
  1. 获取固定属性
  • $("a").prop("href")

      2. 设置属性

  • $('a').prop("title", '我们')

注意:

  • prop 更加适用disabled / checked / selected 等。
自定义属性 attr()
  1. 获取自定义属性
  • $('div').attr('index')

      2. 设置自定义属性

  • $('span').attr('index', 1)
数据缓存 data()
  1. 设置数据缓存
  • $('span').data('uname', 'peach')

      2. 获取数据缓存

  • $('span').data('uname')

注意:

  • data 获取html5 自定义data-index, 第一个 不用写data- , 得到的是数字型。
<!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>
    <script src="jquery.min.js"></script>
</head>

<body>
    <a href="http://www.itcast.cn" title="都挺好">都挺好</a>
    <input type="checkbox" name="" id="" checked>
    <div index="1" data-index="2">我是div</div>
    <span>123</span>
</body>
<script>

    $(function () {
        // 1.获取固定属性名
        console.log($("a").prop("href"));
        console.log($("a").prop('title'));
        // 1.1 设置属性
        $('a').prop("title", '我们')

        // 1.2 prop 更加适用disabled / checked / selected 等。
        $('input').change(function () {
            console.log($(this).prop("checked"));
        })

        // 2 自定义属性
        // 2.1 获取自定义属性
        console.log($('div').attr('data-index'));
        console.log($('div').attr('index'));
        // 2.2 设置自定义属性
        $('span').attr('index', 1)

        // 3 数据缓存 data() 这个里面的数据是存放在元素的内存里面
        $('span').data('uname', 'peach'); // 设置缓存数据
        console.log($('span').data('uname'));  // 获取缓存数据
        // 3.1 data 获取html5 自定义data-index, 第一个 不用写data- , 得到的是数字型。
        console.log($('div').data('index'));

    })

</script>

</html>
示例代码
$(function () {
    // 全选和 全不选
    // 把全选的的状态给其他商品的状态即可
    // 1. 全选
    $('.checkall').change(function () {
        // 1.1 设置其他商品的状态和全选按钮 的状态一致
        console.log($(this).prop('checked'));
        $(".j-checkbox, .checkall").prop("checked", $(this).prop("checked"));

        // 1.2 如果全选则 让所有的商品添加 check-cart-item 类名
        if ($(this).prop("checked")) {
            $('.cart-item').addClass("check-cart-item"); // 添加类名
        } else {
            $(".cart-item").removeClass("check-cart-item");
        }
    })

    // 2. 如果小框里面的数值等于所有数组,则选择全选
    $('.j-checkbox').change(function () {
        console.log($(".j-checkbox:checked").length);

        // 如果当前选择的数量等于商品数量, 则全选选中
        if ($(".j-checkbox:checked").length == $(".j-checkbox").length) {
            $(".checkall").prop("checked", true);
        } else {
            $(".checkall").prop("checked", false);
        }

        if ($(this).prop("checked")) {
            // 让当前的商品添加 check-cart-item 类名
            $(this).parents(".cart-item").addClass("check-cart-item");
        } else {
            // check-cart-item 移除
            $(this).parents(".cart-item").removeClass("check-cart-item");
        }
    })



})
案列-全选与全不选
文本数值

文本属性值常见操作有三种:html() / text() / val() ; 分别对应JS中的 innerHTML 、innerText 和 value 属性。

  1. 普通元素内容html()  对应JS中的 innerHTML
  2. 普通元素文本内容   对应JS中的 innerText
  3. 表单的值                 对应JS中的 value

注意:html() 可识别标签,text() 不识别标签。

<!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>
    <script src="jquery.min.js"></script>
</head>

<body>

    <div>
        <span>我是内容</span>
    </div>
    <input type="text" value="请输入内容">
    <script>
        // 1. 获取设置元素内容 html()
        console.log($('div').html());
        // 1.1 设置HTML内容
        $('div').html('<h1>握手</h1>')

        // 2. 获取设置元素文本内容 text()
        console.log($('div').text());
        // 2.1 设置文本内容
        $('div').text('111')

        // 3. 获取设置表单值 val()
        console.log($('input').val());
        // 3.1 设置属性值
        $('input').val('test')


    </script>
</body>

</html>
示例代码
$(function () {
    // 全选和 全不选
    // 把全选的的状态给其他商品的状态即可
    // 1. 全选
    $('.checkall').change(function () {
        // 1.1 设置其他商品的状态和全选按钮 的状态一致
        console.log($(this).prop('checked'));
        $(".j-checkbox, .checkall").prop("checked", $(this).prop("checked"));

        // 1.2 如果全选则 让所有的商品添加 check-cart-item 类名
        if ($(this).prop("checked")) {
            $('.cart-item').addClass("check-cart-item"); // 添加类名
        } else {
            $(".cart-item").removeClass("check-cart-item");
        }
    })

    // 2. 如果小框里面的数值等于所有数组,则选择全选
    $('.j-checkbox').change(function () {
        console.log($(".j-checkbox:checked").length);

        // 如果当前选择的数量等于商品数量, 则全选选中
        if ($(".j-checkbox:checked").length == $(".j-checkbox").length) {
            $(".checkall").prop("checked", true);
        } else {
            $(".checkall").prop("checked", false);
        }

        if ($(this).prop("checked")) {
            // 让当前的商品添加 check-cart-item 类名
            $(this).parents(".cart-item").addClass("check-cart-item");
        } else {
            // check-cart-item 移除
            $(this).parents(".cart-item").removeClass("check-cart-item");
        }
    })

    // --------------------------------------------------------------------------------
    // 商品 + 计算
    $('.increment').click(function () {
        // 获取到当前多少件商品
        var n = $(this).siblings('.itxt').val()
        n++;
        $(this).siblings(".itxt").val(n);
        // 然后获取到单价标签
        var p = $(this).parents('.p-num').siblings('.p-price').html()
        p = p.substr(1) // 得到单价

        var price = (p * n).toFixed(2); // 保留两位小数
        console.log(price);
        // 然后把价格替换到小计里面
        // 获取到小计标签
        $(this).parents('.p-num').siblings('.p-sum').html("" + price)

    })

    // 商品 - 计算
    $('.decrement').click(function () {
        // 先获取到当前商品数量
        var n = $(this).siblings('.itxt').val()
        // 如果等于1  不做操作
        if (n == 1) {
            return false
        }
        n--;
        // 赋值到数量标签里面
        $(this).siblings(".itxt").val(n);
        // 得到商品的单价
        var p = $(this).parents('.p-num').siblings('.p-price').html().substr(1)
        var price = (p * n).toFixed(2); // 保留两位小数
        $(this).parents('.p-num').siblings('.p-sum').html("" + price)
    })

    // 用户直接再文本款里面输入数量
    $('.itxt').change(function () {
        var n = $(this).val()
        if (n < 0) {
            n = 1
            $(this).val(n);
        }
        // 得到商品的单价
        var p = $(this).parents('.p-num').siblings('.p-price').html().substr(1)
        var price = (p * n).toFixed(2); // 保留两位小数
        $(this).parents('.p-num').siblings('.p-sum').html("" + price)

    })

})
案例-购物车小计计算

元素操作

  1. $('div').each(function (i, domEle) {   })
  • 回调函数第一个是index,第二个是dom元素对象, 要转换为jquer对象

      2. $.each(obj, function (i, ele) {  })

  • $.each() 方法遍历元素 主要用于遍历数据,处理数据
<!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>
    <script src="jquery.min.js"></script>
</head>

<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <script>
        $(function () {
            var sum = 0
            var arr = ["red", "green", "blue"];
            // 第一种遍历元素
            $('div').each(function (i, domEle) {
                // console.log(i, domEle);
                // 回调函数第一个是index,
                // 第二个是dom元素对象,要转换为jquer对象
                $(domEle).css('color', arr[i])
                sum += parseInt($(domEle).text())
            })


            // 第二种 $.each() 方法遍历元素 主要用于遍历数据,处理数据
            $.each(arr, function (i, ele) {
                console.log(i, ele);
            })

            $.each({
                "name": 'peach',
                "age": 12
            }, function (i, ele) {
                console.log(i);  // name
                console.log(ele); // peach

            })


        })
    </script>
</body>

</html>
示例代码
$(function () {
    // 全选和 全不选
    // 把全选的的状态给其他商品的状态即可
    // 1. 全选
    $('.checkall').change(function () {
        // 1.1 设置其他商品的状态和全选按钮 的状态一致
        console.log($(this).prop('checked'));
        $(".j-checkbox, .checkall").prop("checked", $(this).prop("checked"));

        // 1.2 如果全选则 让所有的商品添加 check-cart-item 类名
        if ($(this).prop("checked")) {
            $('.cart-item').addClass("check-cart-item"); // 添加类名
        } else {
            $(".cart-item").removeClass("check-cart-item");
        }
    })

    // 2. 如果小框里面的数值等于所有数组,则选择全选
    $('.j-checkbox').change(function () {
        console.log($(".j-checkbox:checked").length);

        // 如果当前选择的数量等于商品数量, 则全选选中
        if ($(".j-checkbox:checked").length == $(".j-checkbox").length) {
            $(".checkall").prop("checked", true);
        } else {
            $(".checkall").prop("checked", false);
        }

        if ($(this).prop("checked")) {
            // 让当前的商品添加 check-cart-item 类名
            $(this).parents(".cart-item").addClass("check-cart-item");
        } else {
            // check-cart-item 移除
            $(this).parents(".cart-item").removeClass("check-cart-item");
        }
    })

    // --------------------------------------------------------------------------------
    // 商品 + 计算
    $('.increment').click(function () {
        // 获取到当前多少件商品
        var n = $(this).siblings('.itxt').val()
        n++;
        $(this).siblings(".itxt").val(n);
        // 然后获取到单价标签
        var p = $(this).parents('.p-num').siblings('.p-price').html()
        p = p.substr(1) // 得到单价

        var price = (p * n).toFixed(2); // 保留两位小数
        console.log(price);
        // 然后把价格替换到小计里面
        // 获取到小计标签
        $(this).parents('.p-num').siblings('.p-sum').html("" + price)
        getSum()

    })

    // 商品 - 计算
    $('.decrement').click(function () {
        // 先获取到当前商品数量
        var n = $(this).siblings('.itxt').val()
        // 如果等于1  不做操作
        if (n == 1) {
            return false
        }
        n--;
        // 赋值到数量标签里面
        $(this).siblings(".itxt").val(n);
        // 得到商品的单价
        var p = $(this).parents('.p-num').siblings('.p-price').html().substr(1)
        var price = (p * n).toFixed(2); // 保留两位小数
        $(this).parents('.p-num').siblings('.p-sum').html("" + price)
        getSum()
    })

    // 用户直接再文本款里面输入数量
    $('.itxt').change(function () {
        var n = $(this).val()
        if (n < 0) {
            n = 1
            $(this).val(n);
        }
        // 得到商品的单价
        var p = $(this).parents('.p-num').siblings('.p-price').html().substr(1)
        var price = (p * n).toFixed(2); // 保留两位小数
        $(this).parents('.p-num').siblings('.p-sum').html("" + price)
        getSum()

    })

    // ----------------------------------------------------------------
    // 计算总价
    getSum()

    function getSum() {
        // 先定义总件数,总价格
        var count = 0;
        var money = 0;
        $('.itxt').each(function (i, ele) {
            // ele 就是三个图书的dom对象,要转换为jquer对象
            count += parseInt($(ele).val()) // 总件数
        })
        // 修改底部总件数
        $('.amount-sum em').text(count)

        // 修改总价格
        $('.p-sum').each(function (i, ele) {
            // 总价格
            money += parseInt($(ele).text().substr(1))
        })
        // 修改底部总价格
        $(".price-sum em").text("" + money.toFixed(2));


    }

})
案例-购物车计算总价和总件数
创建,删除,修改元素

创建

  • $("<li>创建的li</li>")

添加

  1. 内部添加
  • $('li').append(li) // 放在元素的最后面
  • $('li').prepend(li)  // 放在元素的最前面

      2. 外部添加

  • $('li').after(li) // 放在目标元素的最后面
  • $('li').before(li)   // 放在目标元素的最前面

内部添加元素,生成后,他们是父子关系

外部添加元素,生成后,他们是兄弟关系

删除

  1. $('ul').remove() // 自杀式删除,删除元素本身
  2. $('ul').html('')  // 可以删除匹配的元素里面的子节点 孩子
  3. $('ul').empty() // 匹配删除ele 里面的所有子节点

empty() 和 html()  区别在于html可以设置内容

<!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>
    <script src="jquery.min.js"></script>
</head>

<body>
    <ul>
        <li>原先的li</li>
    </ul>
    <div class="test">我是原先的div</div>

    <script>
        $(function () {
            // 创建元素

            // 1.1 内部添加
            // var li = $("<li>创建的li</li>")
            // $('li').append(li) // 放在元素的最后面 
            // $('li').prepend(li)  // 放在元素的最前面

            // 1.2 外部添加
            // var li = $("<div> 我是外部添加的</div>")
            // $('li').after(li) // 放在目标元素的最后面
            // $('li').before(li)   // 放在目标元素的最前面

            // 删除元素
            // $('ul').remove() // 自杀式删除,删除元素本身
            // $('ul').html('')  // 可以删除匹配的元素里面的子节点 孩子
            $('ul').empty() // 匹配删除ele 里面的所有子节点


        })

    </script>
</body>

</html>
示例代码
$(function () {
    // 全选和 全不选
    // 把全选的的状态给其他商品的状态即可
    // 1. 全选
    $('.checkall').change(function () {
        // 1.1 设置其他商品的状态和全选按钮 的状态一致
        console.log($(this).prop('checked'));
        $(".j-checkbox, .checkall").prop("checked", $(this).prop("checked"));

        // 1.2 如果全选则 让所有的商品添加 check-cart-item 类名
        if ($(this).prop("checked")) {
            $('.cart-item').addClass("check-cart-item"); // 添加类名
        } else {
            $(".cart-item").removeClass("check-cart-item");
        }
    })

    // 2. 如果小框里面的数值等于所有数组,则选择全选
    $('.j-checkbox').change(function () {
        console.log($(".j-checkbox:checked").length);

        // 如果当前选择的数量等于商品数量, 则全选选中
        if ($(".j-checkbox:checked").length == $(".j-checkbox").length) {
            $(".checkall").prop("checked", true);
        } else {
            $(".checkall").prop("checked", false);
        }

        if ($(this).prop("checked")) {
            // 让当前的商品添加 check-cart-item 类名
            $(this).parents(".cart-item").addClass("check-cart-item");
        } else {
            // check-cart-item 移除
            $(this).parents(".cart-item").removeClass("check-cart-item");
        }
    })

    // --------------------------------------------------------------------------------
    // 商品 + 计算
    $('.increment').click(function () {
        // 获取到当前多少件商品
        var n = $(this).siblings('.itxt').val()
        n++;
        $(this).siblings(".itxt").val(n);
        // 然后获取到单价标签
        var p = $(this).parents('.p-num').siblings('.p-price').html()
        p = p.substr(1) // 得到单价

        var price = (p * n).toFixed(2); // 保留两位小数
        console.log(price);
        // 然后把价格替换到小计里面
        // 获取到小计标签
        $(this).parents('.p-num').siblings('.p-sum').html("" + price)
        getSum()

    })

    // 商品 - 计算
    $('.decrement').click(function () {
        // 先获取到当前商品数量
        var n = $(this).siblings('.itxt').val()
        // 如果等于1  不做操作
        if (n == 1) {
            return false
        }
        n--;
        // 赋值到数量标签里面
        $(this).siblings(".itxt").val(n);
        // 得到商品的单价
        var p = $(this).parents('.p-num').siblings('.p-price').html().substr(1)
        var price = (p * n).toFixed(2); // 保留两位小数
        $(this).parents('.p-num').siblings('.p-sum').html("" + price)
        getSum()
    })

    // 用户直接再文本款里面输入数量
    $('.itxt').change(function () {
        var n = $(this).val()
        if (n < 0) {
            n = 1
            $(this).val(n);
        }
        // 得到商品的单价
        var p = $(this).parents('.p-num').siblings('.p-price').html().substr(1)
        var price = (p * n).toFixed(2); // 保留两位小数
        $(this).parents('.p-num').siblings('.p-sum').html("" + price)
        getSum()

    })

    // ----------------------------------------------------------------
    // 删除商品模块
    $('.p-action a').click(function () {
        $(this).parents('.cart-item').remove();
        getSum();

    })
    // 删除选中的商品
    $('.remove-batch').click(function () {
        $('.j-checkbox:checked').parents('.cart-item').remove()
        getSum()
    })

    // 清空购物车
    $('.clear-all').click(function () {
        $('.cart-item').remove()
        getSum()
    })



    // ----------------------------------------------------------------
    // 计算总价
    getSum()

    function getSum() {
        // 先定义总件数,总价格
        var count = 0;
        var money = 0;
        $('.itxt').each(function (i, ele) {
            // ele 就是三个图书的dom对象,要转换为jquer对象
            count += parseInt($(ele).val()) // 总件数
        })
        // 修改底部总件数
        $('.amount-sum em').text(count)

        // 修改总价格
        $('.p-sum').each(function (i, ele) {
            // 总价格
            money += parseInt($(ele).text().substr(1))
        })
        // 修改底部总价格
        $(".price-sum em").text("" + money.toFixed(2));

    }

})
案例-清空删除购物车

尺寸,位置操作

尺寸

语法

用法

width() / height()

匹配元素宽度和高度,只算width和height

innerWidth()  /  innerHieght()

匹配元素宽度和高度,包含padding

outerWidth()  /  outerHeight()

匹配元素宽度和高度,包含padding, border

outerWidth(true)  /  outerHeight(true)

匹配元素宽度和高度,包含padding,border,margin

  • 如果() 里面参数为空,返回相对应值,返回数字类型
  • 参数如果为数字,则是修改相对于的值
  • 参数可以不写单位
<!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>
        div {
            width: 200px;
            height: 200px;
            background-color: pink;
            padding: 10px;
            border: 15px solid red;
            margin: 20px;
        }
    </style>
    <script src="jquery.min.js"></script>
</head>

<body>
    <div></div>
    <script>
        $(function () {
            console.log($('div').height());  //200
            console.log($('div').width(250));  // 修改值

            console.log($('div').innerWidth());  //220  width + padding

            console.log($('div').outerWidth());  // 250   width + padding + border

            console.log($('div').outerWidth(true))  // 290  width + padding + border + margin

        })

    </script>
</body>

</html>
示例代码
位置
  1. offset()  设置或者获取元素偏移量
  • 跟父级别没关系,相对于文档的偏移量
  • 有left, top两个属性, offset().top 获取相对于文档的值
  • 设置元素偏移量: offser({left: 100, top: 100})

      2. position()  获取元素偏移

  • 相对于定位的父亲偏移量坐标
  • 有left, top两个属性, offset().top 获取相对于父亲的值
  • 只能获取
<!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>
        * {
            margin: 0;
            padding: 0;
        }

        .father {
            width: 400px;
            height: 400px;
            background-color: pink;
            margin: 100px;
            overflow: hidden;
            position: relative;
        }

        .son {
            width: 150px;
            height: 150px;
            background-color: purple;
            position: absolute;
            left: 10px;
            top: 10px;
        }
    </style>
    <script src="jquery.min.js"></script>
</head>

<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <script>
        // 相对于文档
        console.log($('.son').offset());
        console.log($('.son').offset().top)
        //设置
        $('.son').offset({
            top: 200,
            left: 200
        })

        // 相对于父亲, 只能获取,不是设置
        console.log($('.son').position());
        console.log($('.son').position().top);

    </script>
</body>

</html>
示例代码

      3. scrollTop() /  scrollLeft()  设置获取元素卷去的距离

  • () 为空是获取,里面是数字是设置
<!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>
        body {
            height: 2000px;
        }

        .back {
            position: fixed;
            width: 50px;
            height: 50px;
            background-color: pink;
            right: 30px;
            bottom: 100px;
            display: none;
        }

        .container {
            width: 900px;
            height: 500px;
            background-color: skyblue;
            margin: 400px auto;
        }
    </style>
    <script src="jquery.min.js"></script>
</head>

<body>
    <div class="back">返回顶部</div>
    <div class="container">
    </div>
    <script>
        $(function () {
            // 设置卷去的头部距离
            $(document).scrollTop(100)

            // 获取box 距离顶部的距离
            var boxTop = $('.container').offset().top
            console.log(boxTop);

            // 注册卷去事件
            $(window).scroll(function () {
                // console.log($(document).scrollTop()); // 这个是文档距离顶部的距离
                // 如果页面的卷去大于 盒子卷去的距离,显示返回顶部按钮
                if ($(document).scrollTop() >= boxTop) {
                    $('.back').fadeIn()
                } else {
                    $('.back').fadeOut()
                }

            })

            // 点击返回顶部,
            $('.back').click(function () {
                $('html, body').stop().animate({
                    scrollTop: 0
                })
            })


        })
    </script>
</body>

</html>
示例代码
$(function () {
    // 当我们点击了小li 此时不需要执行 页面滚动事件里面的 li 的背景选择 添加 current
    // 节流阀  互斥锁 
    var flag = true;
    // 1.显示隐藏电梯导航
    var toolTop = $(".recommend").offset().top;
    toggleTool();

    function toggleTool() {
        if ($(document).scrollTop() >= toolTop) {
            $(".fixedtool").fadeIn();
        } else {
            $(".fixedtool").fadeOut();
        };
    }

    $(window).scroll(function () {
        toggleTool();
        // 3. 页面滚动到某个内容区域,左侧电梯导航小li相应添加和删除current类名


        if (flag) {
            $(".floor .w").each(function (i, ele) {
                if ($(document).scrollTop() >= $(ele).offset().top) {
                    console.log(i);
                    $(".fixedtool li").eq(i).addClass("current").siblings().removeClass();

                }
            })
        }



    });
    // 2. 点击电梯导航页面可以滚动到相应内容区域
    $(".fixedtool li").click(function () {
        flag = false;
        console.log($(this).index());
        // 当我们每次点击小li 就需要计算出页面要去往的位置 
        // 选出对应索引号的内容区的盒子 计算它的.offset().top
        var current = $(".floor .w").eq($(this).index()).offset().top;
        // 页面动画滚动效果
        $("body, html").stop().animate({
            scrollTop: current
        }, function () {
            flag = true;
        });
        // 点击之后,让当前的小li 添加current 类名 ,姐妹移除current类名
        $(this).addClass("current").siblings().removeClass();
    })
})
案例-电梯导航


相关资料: https://github.com/1515806183/html-code/tree/master/jQuery-02

posted @ 2020-03-20 10:50  小白森  阅读(268)  评论(0编辑  收藏  举报