jQuery 操作元素及属性

这篇博客详细介绍了jQuery如何操作元素内容、设置属性、添加删除切换类名、获取或设置value值、遍历元素、处理单选复选框、管理CSS样式、调整宽高、计算偏移量以及获取鼠标位置等。通过这些方法,可以高效地进行DOM操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jQuery中文开发文档

获取或设置元素内容

  • $(selector).html():获取或设置元素的内容,包括标签
  • $(selector).text():获取或设置元素的文本内容,不包括标签
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
       #box{
           width: 200px; height: 200px; border: 1px solid black;
           margin: 50px auto; text-align: center;
       }
       button{
           width: 200px; height: 50px; margin: 0 auto; display: block;
       }
    </style>
    <script>
        $(function(){
            // 1、获取元素内容,返回内容包含标签
            // $("button").click(function(){
            //     console.log($("#box").html());
            // })

            // 2、设置元素内容,重写所有元素内容
            // $("button").click(function(){
            //     $("#box").html("<b>重写内容</b>");
            // })

            // 3、获取元素文本内容,返回不包含标签的文本内容
            // $("button").click(function(){
            //     console.log($("#box").text());
            // })

            // 4、设置元素文本内容,重写所有元素的文本内容
            $("button").click(function(){
                // $("#box").text("<b>重写内容</b>");//标签不会被解析
                $("#box").text("重写文本内容");
            })
        })
    </script>
</head>
<body>
    <div id="box">
        <p>获取或设置元素内容1</p>
        <span>获取或设置元素内容2</span>
    </div>
    <button>点击</button>
</body>
</html>

获取或设置元素属性

  • $(selector).attr(attribute):获取元素属性值

  • $(selector).attr(attribute, value):设置元素属性和属性值

  • $(selector).removeAttr(attribute):移除元素属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
       #box{
           width: 200px; height: 200px; border: 1px solid black;
           margin: 50px auto; text-align: center;
       }
       button{
           width: 200px; height: 50px; margin: 0 auto; display: block;
       }
       .ppp{font-size: 30px;}
       .ppp1{color:red}
       .ppp2{font-weight: 700;}
    </style>
    <script>
        $(function(){
            // 1、获取元素属性值
            // $("button").click(function(){
            //     // var attr = $("#box p").attr("class");
            //     var attr = $("#box p").attr("title");
            //     console.log(attr);
            // })

            // 2、设置元素属性值
            // $("button").click(function(){
            //     var attr = $("#box p").attr("class", "ppp1");
            //     var attr = $("#box p").attr("title", "p_title");
            //     同时设置或添加多个属性
            //     var attr = $("#box p").attr({
            //         class:"ppp1",
            //         title:"p_title",
            //         id:"p_id"
            //     });

            // 使用函数设置属性值,返回一个新的属性值
            //     var attr = $("#box p").attr("title", function(index, value){
            //         return value + "添加的";
            //     });
            //     console.log(attr);
            // })

            // 3、删除元素属性,必须要传参
            $("button").click(function(){
                // $("#box span").removeAttr("title");  
                // $("#box span").removeAttr("id"); 
                // 同时删除多个属性 
                $("#box span").removeAttr("title id");  
            })

            // 4、删除元素类名
            // $("button").click(function(){
                // $("#box span").removeClass("c_span1");
                // $("#box span").removeClass("c_span1 c_span3");
                // 删除全部
                // $("#box span").removeClass();
            // })
        })
    </script>
</head>
<body>
    <div id="box">
        <p class="ppp" title="p_title">获取或设置元素内容1</p>
        <span class="c_span1 c_span2 c_span3" title="s_title" id="s_id">获取或设置元素内容2</span>
    </div>
    <button>点击</button>
</body>
</html>

添加删除切换元素类名

  • $(selector).addClass():添加元素类名

  • $(selector).removeClass():删除元素类名

  • $(selector).toggleClass():切换元素类名,有类名时删除,无类名时添加

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
       #box{
           width: 200px; height: 200px; border: 1px solid black;
           margin: 50px auto; text-align: center;
       }
       button{
           width: 200px; height: 50px; margin: 0 auto; display: block;
       }
       .ppp{font-size: 25px;}
       .ppp1{color:red}
       .ppp2{font-weight: 700;}
    </style>
    <script>
        $(function(){
            // 1、添加元素类名
            $("button").click(function(){
                // 添加一个类名
                // $("#box p").addClass("ppp1");
                // 添加多个类名,用空格隔开
                // $("#box p").addClass("ppp1 ppp2");
            })

            // 2、删除元素类名
            $("button").click(function(){
                // 删除一个类名
                // $("#box span").removeClass("ppp");
                // 删除多个类名
                // $("#box span").removeClass("ppp ppp2");
                // 删除全部
                // $("#box span").removeClass();
            })

            // 3、切换元素类名,有类名时删除,无类名时添加
            $("button").click(function(){
                // $("#box p").toggleClass();
                // $("#box p").toggleClass("ppp");
                // $("#box p").toggleClass("ppp1");
                // $("#box p").toggleClass("ppp1 ppp2");
                $("#box p").toggleClass("ppp ppp1 ppp2");
            })
        })
    </script>
</head>
<body>
    <div id="box">
        <p class="ppp">元素类名操作1</p>
        <span class="ppp ppp1 ppp2">元素类名操作2</span>
    </div>
    <button>点击</button>
</body>
</html>

获取或设置元素value值

  • $(selector).val():获取或设置元素value值
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
       input, button{
           width: 200px; height: 50px; margin: 0 auto; display: block;
       }
    </style>
    <script>
        $(function(){
            // 1、获取元素value值
            $("button").click(function(){
                // console.log($("#inp1").val());
                // console.log($("#inp2").val());
                // console.log($("#inp3").val());
            })

            // 2、设置元素value值
            $("button").click(function(){
                // $("#inp1").val("");
                $("#inp1").val("设置元素value值");
            })
        })
    </script>
</head>
<body>
    <input type="text" id="inp1" value="获取或设置元素value值">
    <br><br>
    <input type="password" id="inp2" value="sdfsdgg">
    <br><br>
    <input type="number" id="inp3" value="123456789">
    <br><br>
    <button>点击</button>
</body>
</html>

获取索引及元素遍历

  • $(selector).index():获取指定元素的索引值

  • $(selector).each():遍历节点,为每个匹配元素执行一个函数,函数可以接收正在遍历元素的索引

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
        span{
            display: block; width: 200px; line-height: 30px;
            text-align: center; margin-top: 20px; background: #ccc;
        }
        button{
            width: 200px; height: 50px; margin-top: 50px;
        }
    </style>
    <script>
        $(function(){
            // 1、index(): 获取指定元素的索引值
            // 如果未找到元素,返回-1
            // $("#box span").click(function(){
            //     var index = $(this).index();
            //     console.log(index);
            // })

            // 2、each():为每个匹配元素规定运行的函数,就是对元素遍历
            // 运行的函数可以接收正在遍历元素的索引
            $("button").click(function(){
                $("#box span").each(function(i){
                    // $(this).text("SPAN");
                    $(this).text("SPAN" + i);
                })
            })

        })
    </script>
</head>
<body>
    <div id="box">
        <span>span1</span>
        <span>span2</span>
        <span>span3</span>
        <span>span4</span>
        <span>span5</span>
        <span>span6</span>
    </div>
    <button>按钮</button>
</body>
</html>

单选框复选框专用选择方法

  • :radio:选择所有单选框元素,等同于[type=‘radio’]
  • :checkbox:选择所有复选框元素,等同于[type=‘checkbox’]
  • :checkbox:选择已被选中的单选框或复选框
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
        span{
            display: block; width: 200px; line-height: 30px;
            text-align: center; margin-top: 20px; background: #ccc;
        }
        button{
            width: 200px; height: 50px; margin-top: 50px;
        }
    </style>
    <script>
        $(function(){
            // 1、:radio 选择所有单选框元素,等同于[type='radio']
            $("button").click(function(){
                // var sex = $("input[type='radio']");
                // var sex = $("input:radio");
                // console.log(sex);
            })

            // 2、:checkbox 选择所有复选框元素,等同于[type='checkbox']
            $("button").click(function(){
                // var sg = $("input[type='checkbox']");
                // var sg = $("input:checkbox");
                // console.log(sg);
            })

            // 3、:checked 选择已被选中的单选框或复选框
            $("button").click(function(){
                var sex = $("input:radio:checked");
                var sg = $("input:checkbox:checked");
                console.log(sex);
                console.log(sg);
            })
        })
    </script>
</head>
<body>
    <!-- 单选开始 -->
    <input type="radio" name="sex" value="1" checked><input type="radio" name="sex" value="0"><input type="radio" name="sex" value="10">人妖
    <!-- 单选结束 -->
    <br><br>
    <!-- 复选开始 -->
    <input type="checkbox" name="sg[]" value="pg">苹果
    <input type="checkbox" name="sg[]" value="xj" checked>香蕉
    <input type="checkbox" name="sg[]" value="pt">葡萄
    <!-- 复选结束 -->
    <br><br>
    <button>按钮</button>
</body>
</html>

获取单选框或复选框的value值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
        span{
            display: block; width: 200px; line-height: 30px;
            text-align: center; margin-top: 20px; background: #ccc;
        }
        button{
            width: 200px; height: 50px; margin-top: 50px;
        }
    </style>
    <script>
        $(function(){
            // 获取单选框value值
            $("button").click(function(){
                var sex = $("input:radio:checked").val();
                console.log(sex);
            });

			// 获取复选框value值
            $("button").click(function(){
                var sg = [];
                $("input:checkbox:checked").each(function(){
                    sg.push($(this).val());
                });
                console.log(sg);
            });
        });
    </script>
</head>
<body>
    <!-- 单选开始 -->
    <input type="radio" name="sex" value="1" checked><input type="radio" name="sex" value="0"><input type="radio" name="sex" value="10">人妖
    <!-- 单选结束 -->
    <br><br>
    <!-- 复选开始 -->
    <input type="checkbox" name="sg[]" value="pg">苹果
    <input type="checkbox" name="sg[]" value="xj" checked>香蕉
    <input type="checkbox" name="sg[]" value="pt">葡萄
    <!-- 复选结束 -->
    <br><br>
    <button>按钮</button>
</body>
</html>

获取或设置CSS样式

  • $(selector).css(“属性名”):获取元素指定属性名的CSS样式
  • $(selector).css(“属性名”, “属性值”):设置元素指定属性名的CSS样式
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
        #box{
            width: 200px; height: 200px; border: 1px solid black;
            margin: 50px auto;
        }
        p{
            width: 200px; text-align: center; margin-top: 20px;
        }
        button{
            display: block; width: 200px; height: 50px;
            margin: 50px auto;
        }
    </style>
    <script>
        $(function(){
            // 1、获取CSS样式
            $("button").click(function(){
                // 获取一个样式
                var s = $("#box p").css('fontWeight');
                var s = $("#box p").css('width');

                // 获取多个样式,返回一个对象
                var s = $("#box p").css(["textAlign", "marginTop"]);
                console.log(s);
            })

            // 2、设置CSS样式
            $("button").click(function(){
                // 设置一个样式
                // $("#box p").css("color", "red");

                // 设置多个样式
                // $("#box p").css("color", "red").css("fontSize", "30px");
                $("#box p").css({
                    color:"red",
                    fontWeight:400,
                    fontSize:"30px",
                    background:"#ccc"
                })
            })
        })
    </script>
</head>
<body>
    <div id="box">
        <p style="font-weight: 700;">获取或设置CSS样式</p>
    </div>
    <button>点击</button>
</body>
</html>

获取或设置元素宽高

  • $(selector).width():获取或设置元素的宽度(不包括内边距、边框或外边距),返回数值类型,可以直接计算
  • $(selector).innerWidth():获取或设置元素的宽度(包括内边距)
  • $(selector).outerWidth():获取或设置元素的宽度(包括内边距和边框)
  • $(selector).height()、$(selector).innerHeight()、$(selector).outerHeight():与宽度同样
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
        #box{
            width: 200px; height: 100px; 
            border: 1px solid black;
            margin: 50px auto;
        }
        button{
            display: block; 
            width: 200px; height: 50px;
            margin: 50px auto;
        }
    </style>
    <script>
        $(function(){
            // 1、获取元素宽高,返回数值类型,可以直接计算
            $("button").click(function(){
                var w = $("#box").width();
                console.log(w);
            });

            // 2、设置元素宽高
            $("button").click(function(){
                // 直接传值设置宽高
                // var w = $("#box").width(400);//参数为数值类型,默认单位像素
                // var w = $("#box").width("400");//参数为字符串类型,默认单位像素
                // var w = $("#box").width("400px");//参数为字符串类型,带单位,其他尺寸也生效

                // 通过函数设置宽高
                // 第一个参数是元素在原先集合中的索引位置,第二个参数为原先的宽高度
                $("#box").width(function(index, oldWidth){
                    return oldWidth+10;
                });

                // $("div").width(function(index, oldWidth){
                //     console.log(index);
                // })//验证第一个参数
            })
        })
    </script>
</head>
<body>
    <div></div>
    <div id="box"></div>
    <button>点击</button>  
</body>
</html>

获取元素在当前视口的偏移量

  • $(selector).offset():获取或设置元素在当前视口的偏移量,返回包含数值类型的top和left属性的对象
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>元素的位置</title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
        div{
            background: red; margin: 10px;
            width: 100px; height: 100px;
            border: solid 3px green;
        }
        input{margin: 50px auto; display: block;}
    </style>
</head>
<body>
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
    <input type="button" value="GET" id="btn1">
    <input type="button" value="Setting" id="btn2">
    <input type="button" value="Setting2" id="btn3">
    <script>
        $(function(){
            // 1、获取元素在当前视口的偏移量
            $("#btn1").click(function(){
                // 返回包含数值类型top和left属性的对象
                var ost = $("#div2").offset();
                console.log(ost);
                console.log(ost.top);
                console.log(ost.left);
            })

            // 2、设置元素在当前视口的偏移量
            $("#btn2").click(function(){
                // 方式一:直接编写位置坐标
                // $("#div2").offset({
                //     top:100,
                //     left:200
                // })

                // 方式二:引用其他已知元素坐标
                $("#div2").offset($("#btn3").offset())
            })

            // 通过函数来设置元素位置
            $("#btn3").click(function(){
                $("div").offset(function(index, oldOffset){
                    alert(index);
                    return {
                        top: oldOffset.top + 100*index,
                        left: oldOffset.left + 100*index
                    }
                })
            })
        })
    </script>
</body>
</html>

获取元素在父元素中的偏移量

  • $(selector).position():获取元素在父元素中的偏移量,返回包含数值类型top和left属性的对象
    1、父元素需要设置position:relative属性,子元素设置position:absolute属性,才能获取元素在父元素中的偏移量
    2、如果父元素没有定位,则获取不到元素到父元素的偏移量,而是获得父元素到当前视口的偏移量
    3、该方法无法用于设置元素的位置
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
        *{margin: 0; padding: 0;}
        #box{
            width: 400px; height: 400px; 
            border: 1px solid black;
            margin: 50px auto;
            position: relative;
        }
        #box p{
            width: 100px; height: 100px; 
            background: red;
            position: absolute; top: 150px; left: 150px;
        }
        button{
            display: block; 
            width: 200px; height: 50px;
            margin: 50px auto;
        }
    </style>
    <script>
        $(function(){
            // 获取元素在父元素中的偏移量
            $("button").click(function(){
                // 返回包含数值类型top和left属性的对象
                var pos = $("#box p").position();
                console.log(pos);                
                console.log(pos.top);                
                console.log(pos.left);               
            });
        });
    </script>
</head>
<body>
    <div id="box">
        <p></p>
    </div>
    <button>点击</button>  
</body>
</html>

获取鼠标相对于当前视口的位置

  • event.pageX / event.pageY:获取鼠标相对于当前视口的位置,获取的位置有两个属性pageX 和 pageY,其中pageX 和pageY必须与事件绑定,接受事件对象
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <script>
        // 获取鼠标相对于当前视口的位置
        // 获取鼠标位置的两个属性pageX 和 pageY
        // pageX 和 pageY必须与事件绑定,接受事件对象
        $(function(){
            $(window).mousemove(function(e){
                var x = e.pageX;
                var y = e.pageY;
                $("title").html(x + " | " + y);
            })
        });
    </script>
</head>
<body>
</body>
</html>

获取鼠标相对于元素的位置

  • event.offsetX / event.offsetY:获取鼠标相对于元素的位置
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
        *{margin: 0; padding: 0;}
        #box{
            width: 400px; height: 400px; 
            border: 1px solid black;
            margin: 50px auto;
        }
    </style>
    <script>
        // 获取鼠标相对于元素的位置
        $(function(){
            $("#box").mousemove(function(e){
                var x = e.offsetX;
                var y = e.offsetY;
                $("title").html(x + " | " + y);
            })
        });
    </script>
</head>
<body>
    <div id="box"></div>
</body>
</html>

获取滚动条的位置

  • $(document).scrollTop():获取滚动条到顶部的距离
  • $(document).scrollLeft():获取滚动条到左侧的距离
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="./jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <style type="text/css">
        *{margin: 0; padding: 0;}
        #box{
            width: 2000px; height: 2000px; 
           background: #ccc;
        }
    </style>
    <script>   
        $(function(){
        	// 获取滚动条的位置
            $(window).scroll(function(){
                var t = $(document).scrollTop();
                var l = $(document).scrollLeft();
                $("title").html(t + " | " + l);
            })
        });
    </script>
</head>
<body>
    <div id="box"></div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值