python Web:jQuery--样式操作、操作节点、循环方法

jQuery操作DOM

基本操作

  • html()
    获取或者设置jQuery对象中的html内容,类似于DOM innerHTML,可识别标签

  • text()
    获取或者设置jQuery对象中的text内容,类似于innerText

    <div id="id1">
        uuuuu
        <p>ppppp</p>
    </div>
    
        console.log($("#id1").html());   //获取标签内的内容(可识别里面的标签)
        console.log($("#id1").text());   //获取标签内的文本
        console.log($("#id1").html("<h1>YUAN</h1>"));  //将#id1 内的内容替换为(可识别标签)<h1>YUAN</h1>
        console.log($("#id1").text("<h1>YUAN</h1>")); //将#id1 内的内容替换为(文本)<h1>YUAN</h1>
    
  • $("").val([val|fn|arr])
    获取或者设置jQuery对象value值(常见表单控件)

    <input type="text" value="123">
    <div value="456"></div>
            //主要针对固有属性
    console.log($(":text").val());//---->123
    console.log($(":text").next().val())//
    $(":text").val("789");//123--->789
    
  • 属性操作

    • attr()
      读取或设置jQuery对象属性值,参数为字符串形式的属性名,自己定义的属性主要用attr

      <div class="div1" con="c1"></div>
      //    console.log($("div").attr("con"))    -->c1
      //    console.log($("div").attr("con","c2"))	--->c1改为c2
      
    • removeAttr()
      移除指定的属性,参数为属性名
      et:
      $(‘div’).removeAttr

    • $("").prop();
      主要用来找一些固有的属性
      <input id="chk1" type="checkbox" />是否可见
      <input id="chk2" type="checkbox" checked="checked" />是否可见
      
      
      
      <script>
      
      //对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
      //对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
      //像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此
      //需要使用prop方法去操作才能获得正确的结果。
      
      
      //    $("#chk1").attr("checked")
      //    undefined
      //    $("#chk1").prop("checked")
      //    false
      
      //  ---------手动选中的时候attr()获得到没有意义的undefined-----------
      //    $("#chk1").attr("checked")
      //    undefined
      //    $("#chk1").prop("checked")
      //    true
      
          console.log($("#chk1").prop("checked"));//false
          console.log($("#chk2").prop("checked"));//true
          console.log($("#chk1").attr("checked"));//undefined
          console.log($("#chk2").attr("checked"));//checked
      </script>
      
    • $("").removeProp();
      <!doctype html>
      <html lang="en">
       <head>
        <meta charset="UTF-8">
        <meta name="Generator" content="EditPlus®">
        <meta name="Author" content="">
        <meta name="Keywords" content="">
        <meta name="Description" content="">
        <title>Document</title>
        <script src="jquery-1.11.3.js"></script>
        <style>
      	#box{
      			width:200px;
      			height:200px;
      			border: 1px solid red;
      	}
      	.c1{
      		color:red;
      		font-size:32px;
      	}
        </style>
       </head>
       <body>
      	<input type="text" id="uname" value="first">
      	<button onclick="showText()">显示</button>
      	<div></div>
      	<h1></h1>
      	<p></p>
      	<input type="text" id="uname" value="second">
       </body>
       <script>
      	function showText(){
      		console.log($('#uname').val());
      		$('div').html('<h1>'+$('#uname').val()+'</h1>');
       
      	}
      	//链式调用 永远返回当前的jQuery对象
      	$('h1').html("西游记").css("text-align","center");
      	
      	$('p').html('<strong>吴承恩</strong>');
       
      	$('p').text('<strong>吴承恩</strong>');
      	
      	//val() 获取表单控件的值,只返回第一个表单元素的value
      	console.log($('input').val());
       
      	//操作属性
      	$('div').attr('id','box');
      	$('h1').attr('class','c1');
      	console.log($('div').attr('id'));
      	
      	//移除属性
      	$('h1').removeAttr('class');
      	console.log($('h1').attr('class'));
      	 </script>
      </html>
      
  • 样式操作

    • attr();
      添加id或class属性,对应选择器,为元素添加样式

    • addClass('className')
      将className作为值添加到元素的class属性上,是可以连缀使用的
      $(‘h1’).addClass(‘c1’).addClass(‘c2’)…

    • removaClass('className');
      移除className
      参数可以省略,表示清空类选择器

    • toggleClass('className')
      切换样式:
      元素如果具备className

      <!doctype html>
      <html lang="en">
       <head>
        <meta charset="UTF-8">
        <meta name="Generator" content="EditPlus®">
        <meta name="Author" content="">
        <meta name="Keywords" content="">
        <meta name="Description" content="">
        <title>Document</title>
        <script src="jquery-1.11.3.js"></script>
        <style>
      	.c2{
      			width:200px;
      			height:200px;
      			border: 1px solid red;
      	}
      	.c1{
      		color:green;
      		font-size:32px;
      	}
        </style>
       </head>
       <body>
      	<h1>jQuery操作样式</h1>
      	<p>切换样式</p>
      	<button onclick="changeStyle()">切换</button>
       </body>
       <script>
       	//添加样式
       	$('h1').addClass('c1').addClass('c2');
       	//$('h1').addClass('c2');
       
       	//移除样式
       	//$('h1').removeClass('c2');
       
      	$('h1').removeClass();
       
      	function changeStyle(){
      		//切换p元素样式
      		$('p').toggleClass('c1');
      	}
       
       
       </script> 
      </html
      

jQuery样式操作

  • attr();
    添加id或class属性,对应选择器,为元素添加样式

  • addClass('className')
    将className作为值添加到元素的class属性上,是可以连缀使用的
    $(‘h1’).addClass(‘c1’).addClass(‘c2’)…

  • removaClass('className');
    移除className
    参数可以省略,表示清空类选择器

  • toggleClass('className')
    切换样式:
    元素如果具备className

  • css()
    获取元素样式属性的值
    et:
    $(‘div’).css(‘width’);

  • css(",")
    设置元素的样式
    et:
    $(‘div’).css(‘width’,‘200px’);

  • css(JSON对象)
    设置元素样式,参数为一组CSS属性
    JSON对象:是一种约束了格式的对象表现形式
    JSON:JavaScript Object Notation

    JSON对象的表示方式

    • JSON对象必须使用{} 括起来
    • 使用键值对来声明数据(属性与值)
    • 所有的属性在声明时必须使用字符串形式" “,
      属性值如果也是字符串,也必须使用” "
    • 属性与值之间使用:连接
    • 多对属性和值之间使用,隔开(最后一个逗号可以省略)
      $('div').css({
      'width:'200px',
      'height':'200px',
      ...
      });
      
      <!doctype html>
      <html lang="en">
       <head>
        <meta charset="UTF-8">
        <meta name="Generator" content="EditPlus®">
        <meta name="Author" content="">
        <meta name="Keywords" content="">
        <meta name="Description" content="">
        <title>Document</title>
        <script src="jquery-1.11.3.js"></script>
       </head>
       <body>
      	<div></div>
      	<h1></h1>
      	<p>JSON对象的格式添加样式</p>
       </body>
       <script>
      	//获取jQuery对象,添加样式
      	$('div').css('width','200px');
      	$('div').css('height','200px');
      	$('div').css('border','1px solid red');
       
      	//链式调用,为h1添加样式
      	$('h1').css('width','300px').css('height','200px').css('background','green');
       
      	//为p元素设置样式
      	$('p').css({
      		'width':'200px',
      		'height':'200px',
      		'font-size':'32px',
      		'background-color':'orange'
      	});
       </script>
      </html>
      

jQuery操作节点

  • children() / children('selector')
    获取某个jQuery对象下所有的子元素,或者获取带有指定选择器的子元素
    注意:只考虑直接子元素,不考虑间接后代元素
  • next() / next('selector')
    获取某jQuery 对象的下一个兄弟元素 / 满足selector的下一个兄弟元素
  • prev() / prev('selector')
    获取某jQuery对象的上一个兄弟元素 / 满足selector 的上一个兄弟元素
  • siblings() / siblings('selector')
    获取某jQuery对象的所有兄弟元素 / 满足selector 的兄弟元素
  • find('selector')
    获取满足selector 的所有后代元素
  • parent()
    获取jQuery对象的父元素
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
  <script src="jquery-1.11.3.js"></script>
 </head>
 <body>
	<h1>静夜思</h1>
	<ul>
		<li class="c1">窗前明月光</li>
		<li>疑是地上霜</li>
		<li>窗前明月光</li>
		<li>疑是地上霜</li>
	</ul>
	<h1 id="h1">李白</h1>
	<ol>
		<li>窗前明月光</li>
		<li>疑是地上霜</li>
		<li>窗前明月光</li>
		<li>疑是地上霜</li>
	</ol>
 
 </body>
 <script>
	//1.获取子节点
	console.log($('body').children());
	console.log($('body').children('h1'));
 
	//2.获取兄弟元素
	console.log($('ul').next());
	//If a selector is provide,it retrieves the next sibling only if it matches the selector
	console.log($('ul').next('#h1'));
 
	console.log($('ul').prev());
 
	//3. 获取所有的兄弟元素
	console.log($('.c1').siblings());
	console.log($('#h1').siblings());
	console.log($('#h1').siblings('ol'));
 
	//4. 获取所有的后代元素,包含直接和间接子元素
	console.log($('ul').find('.c1'));
	console.log($('body').find('li'));
 
	//5. 获取父元素
	console.log($('.c1').parent());

jQuery循环方法

jQuery.each() 函数用于遍历指定的对象和数组。
语法:$.each( object, callback )
Object类型 指定需要遍历的对象或数组。callback:Function类型 指定的用于循环执行的函数。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
	
<script>
$(function () { 
	var obj = {
		"flammable": "inflammable",
		"duh": "no duh"
	};
	$.each( obj, function( key, value ) {
		alert( key + ": " + value );
	});
})
</script>
 
</body>
</html>

正反选(二)(循环的两种方式)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-1.11.3.min.js"></script>
    <script>

             function selectall(){

                 $("table :checkbox").prop("checked",true)
             }
             function cancel(){

                 $("table :checkbox").prop("checked",false)
             }

             function reverse(){


                 //                 var idlist=$("table :checkbox")
//                 for(var i=0;i<idlist.length;i++){
//                     var element=idlist[i];
//
//                     var ischecked=$(element).prop("checked")
//                     if (ischecked){
//                         $(element).prop("checked",false)
//                     }
//                     else {
//                         $(element).prop("checked",true)
//                     }
//
//                 }
//    jquery循环的两种方式
                 //方式一
//                 li=[10,20,30,40]
//                 dic={name:"yuan",sex:"male"}
//                 $.each(li,function(i,x){
//                     console.log(i,x)
//                 })

                 //方式二
//                    $("tr").each(function(){
//                        console.log($(this).html())
//                    })



                 $("table :checkbox").each(function(){

                     $(this).prop("checked",!$(this).prop("checked"));

//                     if ($(this).prop("checked")){
//                         $(this).prop("checked",false)
//                     }
//                     else {
//                         $(this).prop("checked",true)
//                     }
                  

                 });
             }

    </script>
</head>
<body>

     <button onclick="selectall();">全选</button>
     <button onclick="cancel();">取消</button>
     <button onclick="reverse();">反选</button>

     <table border="1">
         <tr>
             <td><input type="checkbox"></td>
             <td>111</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>222</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>333</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>444</td>
         </tr>
     </table>



</body>
</html>

jQuery创建对象

  • $('标签')
    et:
      var $div = $('<div></div>');
      $div.html('动态创建的div');
      $div.attr('id','box');
      $div.css('color','red');
    
    et2:
    var $div2 = $("<div id='box' style = 'color:red;'>动态创建的div</div>");
    
    

模态对话框(二)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .back{
            background-color: rebeccapurple;
            height: 2000px;
        }

        .shade{
            position: fixed;
            top: 0;
            bottom: 0;
            left:0;
            right: 0;
            background-color: coral;
            opacity: 0.4;
        }

        .hide{
            display: none;
        }

        .models{
            position: fixed;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -100px;
            height: 200px;
            width: 200px;
            background-color: gold;

        }
    </style>
</head>
<body>
<div class="back">
    <input id="ID1" type="button" value="click" onclick="action1(this)">
</div>

<div class="shade hide"></div>
<div class="models hide">
    <input id="ID2" type="button" value="cancel" onclick="action2(this)">
</div>


<script src="jquery-1.11.3.min.js"></script>
<script>

    function action1(self){
        $(self).parent().siblings().removeClass("hide");

    }
    function action2(self){
        //$(self).parent().parent().children(".models,.shade").addClass("hide")

        $(self).parent().addClass("hide").prev().addClass("hide")

    }
</script>
</body>
</html>

jQuery 文档处理

  • 内部插入
    将创建好的元素作为子元素插入到网页中
    $obj.append($new)
    将新创建的元素作为最后一个子元素添加
    $obj.prepend($new)
    将创建好的元素作为第一个子元素添加

  • 作为兄弟元素插入
    $obj.after($new)
    将新元素作为$obj 的下一个兄弟元素添加进来

    $obj.before($new)
    将新元素作为$obj 的上一个兄弟元素添加进来

    <!doctype html>
    <html lang="en">
     <head>
      <meta charset="UTF-8">
      <meta name="Generator" content="EditPlus®">
      <meta name="Author" content="">
      <meta name="Keywords" content="">
      <meta name="Description" content="">
      <title>Document</title>
      <script src="jquery-1.11.3.js"></script>
     
     </head>
     <body>
    	<script>
    		var $div = $('<div></div>');
    		$div.attr('id','box');
    		$div.html('动态创建的div');
    		$div.css('color','red');
     
    		var $h1 = $("<h1 id='container' style='color:green;'>动态创建的h1</h1>");
     
    		console.log($div,$h1);
     
    		//将元素添加到网页中
    		$('body').append($div);
    		$('body').prepend($h1);
     
    		//添加兄弟元素
    		var $p = $("<p style='color:blue;'>动态创建段落标签</p>");
    		$div.before($p);
     
    		//创建span标签,添加在h1的后面
    		var $span = $("<span>span普通文本</span>");
    		$h1.after($span);
     
    		//删除元素 remove()
    		$span.remove();
     
    		
    	</script>
     </body>
    </html>
    
    //创建一个标签对象
        $("<p>")
    
    
    //内部插入
    
        $("").append(content|fn)      ----->$("p").append("<b>Hello</b>");
        $("").appendTo(content)       ----->$("p").appendTo("div");
        $("").prepend(content|fn)     ----->$("p").prepend("<b>Hello</b>");
        $("").prependTo(content)      ----->$("p").prependTo("#foo");
    
    //外部插入
    
        $("").after(content|fn)       ----->$("p").after("<b>Hello</b>");
        $("").before(content|fn)      ----->$("p").before("<b>Hello</b>");
        $("").insertAfter(content)    ----->$("p").insertAfter("#foo");
        $("").insertBefore(content)   ----->$("p").insertBefore("#foo");
    
    //替换
        $("").replaceWith(content|fn) ----->$("p").replaceWith("<b>Paragraph. </b>");
    
    //删除
    
        $("").empty()//清除文本内容
        $("").remove([expr])//连带标签一起删除
    
    //复制
    
        $("").clone([Even[,deepEven]])
    

    复制样式条

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
    </head>
    <body>
                <div class="outer">
                    <div class="item">
                            <input type="button" value="+" onclick="add(this);">
                            <input type="text">
                    </div>
                </div>
    
    <script src="jquery-1.11.3.min.js"></script>
        <script>
                //var $clone_obj=$(self).parent().clone();  // $clone_obj放在这个位置可以吗?
                function add(self){
                    // 注意:if var $clone_obj=$(".outer .item").clone();会一遍二,二变四的增加
                     var $clone_obj=$(self).parent().clone();
                     $clone_obj.children(":button").val("-").attr("onclick","removed(this)");
                     $(self).parent().parent().append($clone_obj);
                }
               function removed(self){
    
                   $(self).parent().remove()
    
               }
    
        </script>
    </body>
    </html>
    

css操作

CSS
        $("").css(name|pro|[,val|fn])
    位置
        $("").offset([coordinates])	//相对于视图(窗口)的偏移量,上边和左边
        $("").position()			//position():相对于已经定位的父标签的偏移量
        $("").scrollTop([val])
        $("").scrollLeft([val])
    尺寸
        $("").height([val|fn])
        $("").width([val|fn])
        $("").innerHeight()
        $("").innerWidth()
        $("").outerHeight([soptions])
        $("").outerWidth([options])
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .div1,.div2{
            width: 200px;
            height: 100px;
        }
        .div1{
            border: 5px solid rebeccapurple;
            padding: 20px;
            margin: 2px;
            background-color: antiquewhite;
        }
        .div2{
            background-color: rebeccapurple;
        }

        /*.outer{*/
            /*position: relative;*/
        /*}*/
    </style>
</head>
<body>

<div class="div1"></div>

<div class="outer">
<div class="div2"></div>
</div>



<script src="jquery-3.1.1.js"></script>
<script>
    //offset()相对于视口的偏移量
    console.log($(".div1").offset().top);
    console.log($(".div1").offset().left);

    console.log($(".div2").offset().top);
    console.log($(".div2").offset().left);

    //position():相对于已经定位的父标签的偏移量

    console.log($(".div1").position().top);
    console.log($(".div1").position().left);

    console.log($(".div2").position().top);
    console.log($(".div2").position().left);


    console.log($(".div1").height());
    console.log($(".div1").height("300px"));//可以加参数,设置新的高度
    console.log($(".div1").innerHeight());
    console.log($(".div1").outerHeight());
    console.log($(".div1").outerHeight(true));//添加参数  将margin的数值也计算在其中

</script>
</body>
</html>

返回顶部(按钮)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .div2{
            width: 100%;
            height: 800px;
        }
        .div1{
            width: 40%;
            height: 150px;
            background-color: antiquewhite;
            overflow: auto;
        }
        .div2{
            background-color: rebeccapurple;
        }

         .returnTop{
             position: fixed;
             right: 20px;
             bottom: 20px;
             width: 90px;
             height: 50px;
             background-color: gray;
             color: white;
             text-align: center;
             line-height: 50px;
         }

         .hide{
             display: none;
         }

    </style>
</head>
<body>


<div class="div1">
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
    <h1>1111</h1>
</div>

<div class="div2">
    <button onclick="returnTop()">return</button>
</div>

<div class="returnTop hide" onclick="returnTop()">返回顶部</div>

<script src="jquery-3.1.1.js"></script>
<script>


    window.onscroll=function () {


//        console.log($(window).scrollTop());

        if($(window).scrollTop()>300){
            $(".returnTop").removeClass("hide")
        }else {
            $(".returnTop").addClass("hide")
        }


    };

    function returnTop() {
        $(window).scrollTop(0)

    }

    $(".div2 button").click(function () {
         $(".div1").scrollTop(0)
    })



</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值