天天看點

jQuery筆記jQuery筆記

jQuery筆記

一、 jQuery入門

目标:

  • 能夠說出什麼是jQuery
  • 能夠說出jquery的優點
  • 能夠簡單使用jquery
  • 能夠說出dom對象和jquery對象的差別

1、jQuery概述

1-1 JavaScript庫

倉庫:可以把很多東西放到這個庫裡面。找東西隻需要到倉庫裡面查找就可以了。

JavaScript庫:就是library,是一個封裝好的特定的集合(方法和函數)。從封裝一大堆函數的角度了解庫,就是在這個庫中,封裝了很多預先定義好的函數在裡面,比如:動畫animate、hide、show,比如擷取元素等。

簡單了解:就是一個js檔案,裡面對我們原生js代碼進行了封裝,存放到裡面。這樣我們就可以快速高效的使用這些封裝好的功能了。

比如jQuery,就是為了快速友善的操作dom,裡面基本都是函數(方法)。

常見的JavaScript庫:

jQuery、Prototype、YUI、Dojo、Ext JS、移動端的zepto

這些庫都是對原生js的封裝,内部都是用js實作的,我們主要學習的是jQuery。

1-2 jQuery的概念

jQuery是一個快速、簡潔的js庫,其設計的宗旨是“write less,do more”,即倡導寫更少的代碼,做更多的事情。

j就是javascript;Query查詢;意思是查詢js,把js中的dom操作做了封裝,我們可以快速的查詢使用裡面的功能。

jQuery封裝了js常用的功能代碼,優化了dom操作、事件處理、動畫設計和Ajax互動。

學習 jQuery本質:就是學習調用這些函數(方法)。

jQuery出現的目的就是加快前端人員的開發速度,我們可以非常友善的調用和使用它,進而提高開發效率。

jQuery的優點:

  • 輕量級,核心檔案才幾十kb,不會影響加載速度。
  • 跨浏覽器相容,基本相容了現在主流的浏覽器
  • 鍊式程式設計、隐式疊代
  • 對事件、樣式、動畫支援,大大簡化了dom操作
  • 支援插件擴充開發,有着豐富的第三方的插件,例如:樹形菜單、日期控件、輪播圖等
  • 免費、開源

2、jQuery的基本使用

2-1 jQuery的下載下傳

官網位址:https://jquery.com

版本:

  • 1x:相容ie678等低版本浏覽器,官網不再更新
  • 2x:不相容ie678等低版本浏覽器,官網不再更新
  • 3x:不相容ie678等低版本浏覽器,是官方主要更新維護的版本

各個版本的下載下傳:http://code.jquery.com

2-2 jQuery的使用步驟

  • 引入 jQuery檔案
  • 使用即可

2-3 jQuery的入口函數

$(function(){
	```//此處是頁面dom加載完成的入口
})
//還有一種方法
$(document).ready(function(){
	```//此處是頁面dom加載完成的入口
})
           
  • 等着dom結構渲染完畢即可執行内部代碼,不必等到所有外部資源加載完成, jQuery幫我們完成了封裝。
  • 相當于原生js中的DOMContentLoaded。
  • 不同于原生js中的load事件是等頁面文檔、外部的js檔案、css檔案、圖檔加載完畢才執行内部代碼。
  • 更推薦使用第一種方式
<script>
			//1.等着頁面dom加載之後再去執行js
			/*$(document).ready(function(){
				$("div").hide();
			})*/
			//2.等着dom加載完畢之後再去執行js 同樣的效果  推薦使用這個
			$(function(){
				$("div").hide();
			})
</script>
           

2-4 jQuery的頂級對象$

是 j Q u e r y 的 别 稱 , 在 代 碼 中 可 以 使 用 j Q u e r y 代 替 是 jQuery的别稱,在代碼中可以使用 jQuery代替 是jQuery的别稱,在代碼中可以使用jQuery代替,但一般為了友善,通常都直接使用$.

是 j Q u e r y 的 頂 級 對 象 , 相 當 于 原 生 j s 中 的 w i n d o w 。 把 元 素 利 用 是 jQuery的頂級對象,相當于原生js中的window。把元素利用 是jQuery的頂級對象,相當于原生js中的window。把元素利用包裝成 jQuery對象,就可以調用 jQuery的方法。

<body>
		<div></div>
		<script>
			//1.$是jquery的别稱
			/*$(function(){
				$("div").hide();
			})*/
			jQuery(function(){
				jQuery("div").hide();
			})
			//這兩種寫法的效果是相同的,一般我們還是喜歡用$,比較簡單
			//2.$也同時是jquery的頂級對象
		</script>
</body>
           

2-5 jQuery對象和DOM對象

  • 用原生js擷取來的對象就是dom對象
  • jQuery方法擷取的元素就是jQuery對象
  • jQuery對象的本質是:利用$對DOM對象包裝後産生的對象(僞數組形式存儲)。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" ></script>
		<style>
			div{
				width:200px;
				height:200px;
				background-color: pink;
			}
		</style>
	</head>
	<body>
		<div></div>
		<span></span>
		<script>
			//dom對象: 用原生js擷取過來的對象就是dom對象
			var myDiv=document.querySelector("div");//myDiv就是DOM對象
			var mySpan=document.querySelector("span");//mySpan就是DOM對象
			console.dir(myDiv);
			//jquery對象: 用jqery方式擷取過來的就是jquery的對象 本質:通過$把dom元素進行了包裹
			$("div");//$("div")是一個jquery的對象
			$("span");//$("span")是一個jquery的對象
			console.dir($("div"));
			//jquery對象隻能使用j的方法,dom對象隻能使用原生js的方法和屬性
			myDiv.style.display="none";
			//myDiv.hide();報錯
			$("span").hide();
			$("span").style.display="none";//報錯
		</script>
	</body>
</html>


           

dom對象與jQuery對象之間是可以互相轉換的。

因為原生js比jQuery更大,原生的一些屬性和方法jQuery沒有給我們封裝,要想使用這些屬性和方法需要把jQuery對象轉換為dom對象才能使用。

  • dom對象轉換為jQuery對象:$(DOM對象)
    $('div')
               
  • jQuery對象轉換為dom對象(兩種方式)
    $('div')[index]   index是索引号
    $('div').get(index)  
               
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" ></script>
		<style>
			div{
				width: 200px;
				height: 200px;
				background-color: pink;
			}
		</style>
	</head>
	<body>
		<div></div>
		<script>
			//1.用原生js擷取dom對象
			//var div=document.querySelector("div");
			//dom對象轉化為jquery對象
			/*$(div).hide();
			console.log($(div));*/
			//2.用jQuery方式擷取
			$("div");
			//把j轉換為dom對象
			$("div")[0].style.backgroundColor="purple";
			$("div").get(0).style.width="500px";
		</script>
	</body>
</html>

           

二、jQuery常用API

目标:

  • 能夠寫出常用的jQuery選擇器
  • 能夠操作jQuery樣式
  • 能夠寫出常用的jQuery動畫
  • 能夠操作jQuery屬性
  • 能夠操作jQuery元素
  • 能夠操作jQuery元素尺寸、位置

1、jQuery選擇器

1-1 jQuery基礎選擇器

原生js擷取元素方式很多,很雜,而且相容性情況不不一緻,是以jQuery給我們做了封裝,是擷取元素統一标準。

$('選擇器')//裡面選擇器直接寫css選擇器即可,但是要加引号
           
名稱 用法 描述
ID選擇器 $(’#id’) 擷取指定id的元素
全選選擇器 $("*") 比對所有元素
類選擇器 $(’.class’) 擷取同一類class的元素
标簽選擇器 $(‘div’) 擷取同一類标簽的所有元素
并集選擇器 $(‘div,p,li’) 選取多個元素
交集選擇器 $(‘li.current’) 交集元素

1-2 jQuery層級選擇器

名稱 用法 描述
子代選擇器 $(‘ul>li’) 使用>号,擷取親兒子層級的元素;注意,并不會擷取孫子層級的元素
後代選擇器 $(‘ul li’) 使用空格,代表後代選擇器,擷取ul下的所有li元素,包括孫子等
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" ></script>
	</head>
	<body>
		<div id="head">我是div</div>
		<div class="nav">我是nav div</div>
		<p>我是p</p>
		<ol>
			<li>我是ol的</li>
			<li>我是ol的</li>
			<li>我是ol的</li>
			<li>我是ol的</li>
		</ol>
		<ul>
			<li>我是ul的</li>
			<li>我是ul的</li>
			<li>我是ul的</li>
			<li>我是ul的</li>
		</ul>
		<script>
			$(function(){
				//選取class為nav的div
				$(".nav");
				console.log($(".nav"));
				//擷取id為head的div
				$("#head");
				console.log($("#head"))
				//擷取p标簽
				$("p");
				//擷取ul下所有的li
				console.log($("ul li"))
			})
			
		</script>
	</body>
</html>

           

1-3隐式疊代(重要)

jQuery設定樣式

$("div").css("屬性","值")
           

周遊内部dom元素(僞數組形式存儲)的過程就叫做隐式疊代。

簡單了解:給比對到的所有元素進行循環周遊,執行相應的方法,而不用我們再進行循環,簡化我們的操作,友善我們調用。

<body>
		<div>驚喜不,意外不</div>
		<div>驚喜不,意外不</div>
		<div>驚喜不,意外不</div>
		<div>驚喜不,意外不</div>
		<ul>
			<li>相同的操作</li>
			<li>相同的操作</li>
			<li>相同的操作</li>
			<li>相同的操作</li>
		</ul>
		<script>
			$(function(){
				//1.擷取4個div元素
				console.log($("div"))
				//2.給4個div的背景顔色設定成粉色
				$("div").css("background","pink");
				$("ul li").css("color","red");
				//3.隐式疊代就是把比對的所有元素内部進行周遊循環,給每一個元素添加css這個方法
			})
		</script>
</body>
           

1-4 篩選選擇器

文法 用法 描述
:first $(“li:first”) 擷取第一個li元素
:last $(“li:last”) 擷取最後一個li元素
:eq(index) $(“li:eq(2)”) 擷取到的li元素中,選擇索引号為2的元素,索引号index從0開始
:odd $(“li:odd”) 擷取到的li元素中,選擇索引号為奇數的元素
:even $(“li:even”) 擷取到的li元素中,選擇索引号為偶數
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
	</head>
	<body>
		<ul>
			<li>今天天氣太冷了吧</li>
			<li>今天天氣太冷了吧</li>
			<li>今天天氣太冷了吧</li>
			<li>今天天氣太冷了吧</li>
			<li>今天天氣太冷了吧</li>
			<li>今天天氣太冷了吧</li>
		</ul>
		<ol>
			<li>今天天氣太冷了吧</li>
			<li>今天天氣太冷了吧</li>
			<li>今天天氣太冷了吧</li>
			<li>今天天氣太冷了吧</li>
			<li>今天天氣太冷了吧</li>
			<li>今天天氣太冷了吧</li>
		</ol>
		<script>
			$(function(){
				//選取的第一個元素
				$("ul li:first").css("color","red");
				//選取最後一個元素
				$("ul li:last").css("color","burlywood");
				//選取第四個元素,索引号從0開始,是以索引号3是元素的第四個元素
				$("ul li:eq(3)").css("font-size","20px");
				//給ol的奇數元素添加樣式 索引号為 1,3,5
				$("ol li:odd").css("color","pink")
				//給ol的偶數元素添加樣式 索引号為 0,2,4
				$("ol li:even").css("color","blue")
			})
		</script>
	</body>
</html>

           

1-5 jQuery篩選方法(重點)

重點記住這幾個方法:parent()、children()、find()、siblings()、eq()

文法 用法 說明
parent() $(“li”).parent() 查找父級
children(selector) $(“ul”).children(“li”) 相當于$(“ul>li”),最近一級(親兒子)
find(selector) $(“ul”).find(“li”) 相當于$(“ul li”),後代選擇器
siblings(selector) $(".first").siblings(“li”) 查找兄弟節點,不包括自己本身
nextAll([expr]) $(".first").nextAll() 查找目前元素之後所有的同輩元素
prevtAll([expr]) $(".first").prevtAll() 查找目前元素之前所有的同輩元素
hasClass(class) $(“div”.hasClass(‘protected’) 檢查目前元素是否含有某個特定的類,如果有,則傳回true
eq(index) $(“li”).eq(2) 相當于$(“li:eq(2)”),index從0開始
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" ></script>
	</head>
	<body>
		<div class="head">
			<div class="father">
				<div class="son"></div>
			</div>
		</div>
		
		<div class="nav">
			<p>我是p</p>
			<div>
				<p>我是div的p</p>
			</div>
		</div>
		<script>
			$(function(){
				//1.擷取父親元素parent() 擷取的是最近的父元素,就是親爸爸
				console.log($(".son").parent());
				//2.擷取子元素
				//(1)選取親兒子 chilren(),代表的是親兒子,相當于ul>li 子代選擇器
				$(".nav").children("p").css("color","red");
				//(2)find()選取所有的孩子和孫子  相當于後代選擇器ul li
				$(".nav").find("p").css("background","blue");
			})
		</script>
	</body>
</html>

           
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
		<style>
			.current{
				background-color: red;
			}
		</style>
	</head>
	<body>
		<ol>
			<li>我是ol的</li>
			<li>我是ol的</li>
			<li class="item">我是ol的</li>
			<li>我是ol的</li>
			<li>我是ol的</li>
			<li>我是ol的</li>
		</ol>
		<ul>
			<li>我是ul的</li>
			<li>我是ul的</li>
			<li>我是ul的2</li>
			<li>我是ul的</li>
			<li>我是ul的</li>
			<li>我是ul的</li>
		</ul>
		<div class="current">我有current類名</div>
		<div>我沒有類名</div>
		<script>
			$(function(){
				//1.兄弟元素siblings()  除了自身以外的所有親兄弟
				//$("ol .item").siblings("li").css("color","pink")
				//2.prevAll()目前元素之前的同輩元素
				$("ol .item").prevAll().css("color","pink");
				//3.nextAll() 目前元素之後的同輩元素
				$("ol .item").nextAll().css("color","blue");
				//4.第幾個元素
				//利用選擇器
				//$("ul li:eq(2)").css("color","pink")
				//利用選擇選擇方法   更推薦這個方法
				$("ul li").eq(2).css("color","pink")
				//5.判斷是否有類名
				console.log($("div:first").hasClass("current"));//true
				console.log($("div").eq(1).hasClass("current"));//false
			})
		</script>
	</body>
</html>

           
jQuery筆記jQuery筆記
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
		<style>
			ul,li,a{
				padding:0;
				margin:0;
			}
			li{
				list-style: none;
			}
			a{
				text-decoration: none;
			}
			.nav{
				width:500px;
				height:30px;
				margin:100px auto;
			}
			.list{
				float: left;
				position: relative;
			}
			.list a{
				display: block;
				width:70px;
				height:30px;
				line-height: 30px;
				text-align: center;
				color:#4c4c4c;
				font-weight: 400;
				font-size:14px;
				
			}
			.list a:hover{
				background-color: #ccc;
				
			}
			.itme{
				position: absolute;
				left:0;
				top: 30px;
				display: none;
			}
			.itme li{
				border:1px solid orange;
				border-top:none;
			}
			.itme li a{
				background-color: #fff;
			}
			.itme li a:hover{
				background-color: orange;
				color:#fff;
			}
		</style>
	</head>
	<body>
		<ul class="nav">
			<li class="list">
				<a href="#">微網誌</a>
				<ul class="itme">
					<li><a href="#">私信</a></li>
					<li><a href="#">評論</a></li>
					<li><a href="#">@我</a></li>
				</ul>
			</li>
			<li class="list">
				<a href="#">部落格</a>
				<ul class="itme">
					<li><a href="#">部落格評論</a></li>
					<li><a href="#">未讀提醒</a></li>
				</ul>
			</li>
			<li class="list">
				<a href="#">郵箱</a>
				<ul class="itme">
					<li><a href="#">免費郵箱</a></li>
					<li><a href="#">企業郵箱</a></li>
					<li><a href="#">vip郵箱</a></li>
					<li><a href="#">新浪郵箱</a></li>
				</ul>
			</li>
			<li class="list">
				<a href="#">網站導航</a>
			</li>
		</ul>
		<script>
			$(function(){
				$(".nav>li").mouseover(function(){
					//$(this)目前元素  this不加引号
					$(this).children("ul").show()
				})
				$(".nav .list").mouseout(function(){
					$(this).children("ul").hide()
				})
			})
		</script>
	</body>
</html>


           

1-6 jQuery裡面的排他思想

想要多選一的效果,排他思想:目前元都設定樣式,其他的兄弟元素清除樣式。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="jquery.min.js" ></script>
	</head>
	<body>
		<button>點選</button>
		<button>點選</button>
		<button>點選</button>
		<button>點選</button>
		<button>點選</button>
		<button>點選</button>
		<button>點選</button>
		<script>
			$(function(){
				//運用隐式疊代 給所有的按鈕綁定事件
				$("button").click(function(){
					//目前的元素變換背景顔色
					$(this).css("background","red");
					//其他的元素的背景元素不變
					$(this).siblings("button").css("background","")
				})
			})
		</script>
	</body>
</html>

           
jQuery筆記jQuery筆記
<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="js/jquery.min.js" ></script>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
            font-size: 12px;
        }
        
        ul {
            list-style: none;
        }
        
        a {
            text-decoration: none;
        }
        
        .wrapper {
            width: 250px;
            height: 248px;
            margin: 100px auto 0;
            border: 1px solid pink;
            border-right: 0;
            overflow: hidden;
        }
        
        #left,
        #content {
            float: left;
        }
        #left li a {
            display: block;
            width: 48px;
            height: 27px;
            border-bottom: 1px solid pink;
            line-height: 27px;
            text-align: center;
            color: black;
        }
        #left li a:hover{
        	background-color: red;
        }
        #content {
            border-left: 1px solid pink;
            border-right: 1px solid pink;
        }
    </style>
    <script>
        $(function() {
            // 1. 滑鼠經過左側的小li 
            $("#left li").mouseover(function() {
                // 2. 得到目前小li 的索引号
                var index = $(this).index();
                console.log(index);
                // 3. 讓我們右側的盒子相應索引号的圖檔顯示出來就好了
                // $("#content div").eq(index).show();
                // 4. 讓其餘的圖檔(就是其他的兄弟)隐藏起來
                // $("#content div").eq(index).siblings().hide();
                // 鍊式程式設計
                $("#content div").eq(index).show().siblings().hide();

            })
        })
    </script>
</head>

<body>
    <div class="wrapper">
        <ul id="left">
            <li><a href="#">女靴</a></li>
            <li><a href="#">雪地靴</a></li>
            <li><a href="#">冬裙</a></li>
            <li><a href="#">呢大衣</a></li>
            <li><a href="#">毛衣</a></li>
            <li><a href="#">棉服</a></li>
            <li><a href="#">女褲</a></li>
            <li><a href="#">羽絨服</a></li>
            <li><a href="#">牛仔褲</a></li>
        </ul>
        <div id="content">
            <div>
                <a href="#"><img src="img/冬靴.png" width="200" height="250" /></a>
            </div>
            <div>
                <a href="#"><img src="img/雪地靴.png" width="200" height="250" /></a>
            </div>
            <div>
                <a href="#"><img src="img/冬裙.png" width="200" height="250" /></a>
            </div>
            <div>
                <a href="#"><img src="img/毛呢大衣.png" width="200" height="250" /></a>
            </div>
            <div>
                <a href="#"><img src="img/毛衣.png" width="200" height="250" /></a>
            </div>
            <div>
                <a href="#"><img src="img/棉服.png" width="200" height="250" /></a>
            </div>
            <div>
                <a href="#"><img src="img/女褲.png" width="200" height="250" /></a>
            </div>
            <div>
                <a href="#"><img src="img/羽絨服.png" width="200" height="250" /></a>
            </div>
            <div>
                <a href="#"><img src="img/牛仔褲.png" width="200" height="250" /></a>
            </div>
        </div>
    </div>
</body>

</html>
           

1-7 鍊式程式設計

鍊式程式設計是為了節省代碼量,看起來更優雅。

$(this).css('color','red').sibling().css('color','');
           

使用鍊式程式設計一定注意是哪個對象執行樣式

<body>
		<button>點選</button>
		<button>點選</button>
		<button>點選</button>
		<button>點選</button>
		<button>點選</button>
		<button>點選</button>
		<button>點選</button>
		<script>
			$(function(){
				$("button").click(function(){
					//讓目前的元素變色
					/*$(this).css("background","pink");
					//讓其他的兄弟不變色
					$(this).siblings().css("background","");*/
					//鍊式程式設計
					$(this).css("color","pink").siblings().css("color","");
					//這句話的意思是:目前的元素變顔色,其他的兄弟不變顔色
				})
			})
		</script>
</body>
           

2、jQuery樣式操作

2-1 操作css方法

jQuery可以使用css方法來修改簡單元素樣式;也可以操作類,修改多個樣式。

  • 參數隻寫屬性名,則是傳回屬性值
    $(this).css(‘color’);
               
  • 參數是屬性名,屬性值,逗号分隔,是設定一組樣式,屬性必須加引号,隻如果是數字可以不加引号和機關。
    $(this).css('color','red')
               
  • 參數可以是對象形式,友善設定多組樣式。屬性名和屬性值使用冒号隔開,屬性可以不用加引号
    $(this).css({
    	'color':'red',
    	'font-size':'20px'
    })
               
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
		<style>
			div{
				width:200px;
				height:200px;
				background-color: pink;
			}
			p{
				width:100px;
				height:100px;
				background-color: blue;
				color:red;
			}
		</style>
	</head>
	<body>
		<div>1243</div>
		<p>我是p</p>
		<script>
			$(function(){
				
				//參數隻寫屬性名,則傳回屬性值
				$("div").css("width");
				console.log($("div").css("width"));//200px
				//$("div").css("width","300px")
				//$("div").css("width",300);//屬性名一定要加引号,屬性值如果是數字的話可以不加引号
				$("div").css({
					"width": 300,
					"height":300,
					"font-size":"30px",
					"background-color": "blue"//屬性名如果加了引号,可以不用駝峰命名法
					//backgroundColor:"red"
					//屬性名可以不加引号,但是複合屬性需要用駝峰命名法,屬性值不是數字需要加引号,
				})
				$("p").css({
					width:"500px",
					height:"400px",
					backgroundColor:"purple",
					fontSize:"30px",
					color:"#fff"
				})
			})
		</script>
	</body>
</html>

           

2-2 設定類樣式方法

作用等同于以前的classList,可以操作類樣式,注意操作類裡面的參數不要加點。

1.添加類

$("div).addClass('current');
           

2.移動類

$('div').removeClass('current')
           

3.切換類

$('div').toggleClass('current')
           
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" ></script>
		<style>
			div{
				width:150px;
				height:150px;
				background-color: pink;
				margin:100px auto;
				transition: all 0.5s;
			}
			.current{
				background-color: red;
				transform: rotate(360deg);
			}
		</style>
	</head>
	<body>
		<div class="current"></div>
		<script>
			$(function(){
				$("div").click(function(){
					//1.添加類 addClass()
					//$(this).addClass("current");
					//2.删除類removeClass()
					//$(this).removeClass("current");
					//3.切換類 toggleClass()
					$(this).toggleClass("current")
				})
			})
		</script>
	</body>
</html>

           

tab欄切換案例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
		<style>
			ul,li{
				padding:0;
				margin:0;
			}
			.tab{
				width:988px;
				margin:100px auto;
			}
			
			ul{
				width:988px;
				height:40px;
				background-color: gainsboro;
				border:1px solid #ccc;
			}
			
			li{
				height:40px;
				list-style: none;
				float: left;
				padding:0 10px;
				line-height: 40px;
				cursor: pointer;
			}
			.tab_list .current{
				background-color: red;
				color:#fff;
			}
			.tab_con{
				padding-top:1px;
			}
			.item{
				display: none;
			}
		</style>
	</head>
	<body>
		<div class="tab">
			<div class="tab_list">
				<ul>
					<li class="current">商品介紹</li>
					<li>規格與包裝</li>
					<li>售後保障</li>
					<li>商品評價(5000)</li>
					<li>手機社群</li>
				</ul>
			</div>
			<div class="tab_con">
				<div class="item" style="display: block;">
					商品介紹子產品
				</div>
				<div class="item">
					規格與包裝子產品
				</div>
				<div class="item">
					售後保障子產品
				</div>
				<div class="item">
					商品評價(5000)子產品
				</div>
				<div class="item">
					手機社群子產品
				</div>
			</div>
		</div>
		<script>
			$(function(){
				//鍊式程式設計
				$(".tab_list li").click(function(){
					//點選上面的li,目前的li添加current類,其餘的li移除類名。
					$(this).addClass("current").siblings().removeClass("current");
					//點選的同時,得到目前的li的索引号
					var index=$(this).index();
					//讓下部裡賣弄相應的索引号的item顯示,其餘的item隐藏
					$(".tab_con div").eq(index).show().siblings().hide()
				})
			})
		</script>
	</body>
</html>

           

2-3 類操作與className差別

原生js中className會覆寫元素原先裡面的類名。

jquery裡面類操作隻是對指定類進行操作(追加或删除),不影響原先的類名。

<body>
		<div class="one"></div>
		<script>
			$("div").addClass("two");//one two
			$("div").removeClass("one");//one
		</script>
</body>
           

3、jQuery效果

jQuery給我們封裝了很多動畫效果,最常見的如下:

顯示與隐藏: show() hide() toggle()

滑動: slideDown() slideUp() slideToggle()

淡入淡出:fadeIn() fadeOut() fadeToggle() fadeTo()

自定義動畫:animate()

3-1 顯示隐藏效果

顯示文法:

  • 顯示文法規範
    show(speed,easeing,fn)
               
  • 顯示參數
    • 參數都可以省略,無動畫直接顯示
    • speed:三種預定速度之一的字元串(‘show’,‘normal’,or’fast’)或表示動畫時長的毫秒數值(如:1000)。
    • easeing:用來指定切換效果,預設是‘swing’,可用參數‘liear’
    • fn:回調函數,在動畫完成時執行的函數,每個元素執行一次。

隐藏文法:

隐藏文法規範

hide(speed,easeing,fn) 參數如上
           

切換效果文法:

toggle(speed,easeing,fn);
//參數和以上一樣
           
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
		<style>
			div{
				width:138px;
				height:300px;
				background-color: pink;
				display: none;
			}
		</style>
	</head>
	<body>
		<button>顯示</button>
		<button>隐藏</button>
		<button>切換</button>
		<div></div>
		<script>
			$(function(){
				$("button").eq(0).click(function(){
					$("div").show(1000);
				})
				$("button").eq(1).click(function(){
					$("div").hide(1000);
				})
				$("button").eq(2).click(function(){
					$("div").toggle(1000);
				})
			})
			//一般情況下,我們不加參數,直接使用 
		</script>
	</body>
</html>

           

3-2 滑動效果

  • 下滑效果文法規範 slideDown(speed,easeing,fn)
  • 上滑效果文法規範 slideUp(speed,easeing,fn)
  • 滑動切換效果 slideToggle((speed,easeing,fn)

參數都可以省略,無動畫直接顯示

speed:三種預定速度之一的字元串(‘show’,‘normal’,or’fast’)或表示動畫時長的毫秒數值(如:1000)。

easeing:用來指定切換效果,預設是‘swing’,可用參數‘liear’

fn:回調函數,在動畫完成時執行的函數,每個元素執行一次

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
		<style>
			div{
				width:138px;
				height:300px;
				background-color: pink;
				display: none;
			}
		</style>
	</head>
	<body>
		<button>下拉滑動</button>
		<button>上拉滑動</button>
		<button>切換滑動</button>
		<div></div>
		<script>
			$(function(){
				$("button").eq(0).click(function(){
					//下滑動slideDown()
					$("div").slideDown()
				})
				$("button").eq(1).click(function(){
					//上滑動slideUp()
					$("div").slideUp()
				})
				$("button").eq(2).click(function(){
					//滑動切換 slideToggle()
					$("div").slideToggle()
				})
			})
			
		</script>
	</body>
</html>

           

3-3 事件切換

hover(over,out)

  • over:滑鼠移到元素上要觸發的函數(相當于mouseenter)
  • out:滑鼠移除元素要觸發的函數(相當于mouseleave)
//新浪下拉菜單案例,詳細的案例在上面的内容中,以下隻是script的部分
		<script>
			$(function(){
				/*$(".nav>li").mouseover(function(){
					//$(this)目前元素  this不加引号
					$(this).children("ul").slideDown();
				})
				$(".nav>li").mouseout(function(){
					$(this).children("ul").slideUp()
				})*/
				//時間切換 hover 就是滑鼠經過和離開的複合寫法
				/*$(".nav>li").hover(function(){
					$(this).children("ul").slideDown(200);
				},function(){
					$(this).children("ul").slideUp(200)
				})*/
				//事件切換 hover 如果隻寫一個函數,那麼滑鼠經過和滑鼠離開都會觸發
				$(".nav>li").hover(function(){
					$(this).children("ul").slideToggle(200)
				})
			})
	</script>
           

3-4 動畫列隊及其停止排隊方法

  • 動畫或效果列隊

    動畫或者效果一旦觸發就會執行,如果多次觸發,就造成多個動畫或者效果排隊執行。

  • 停止排隊 stop()

    stop()方法用于停止動畫或效果。

    注意:stop()寫到動畫或者效果的前面,相當于停止結束上一次的動畫。

    //以上面的案例為例
    $(".nav>li").hover(function(){
    	$(this).children("ul").stop().slideToggle(200)
    })
               

3-5 淡出淡入效果

1.淡出效果:fadeOut(speed,easeing,fn)

2.淡入效果:fadeIn(speed,easeing,fn)

3.淡入淡出切換效果:fadeToggle(speed,easeing,fn)

注意:括号裡面的參數都是相同的

  • 參數都可以省略,無動畫直接顯示
  • speed:三種預定速度之一的字元串(‘show’,‘normal’,or’fast’)或表示動畫時長的毫秒數值(如:1000)。
  • easeing:用來指定切換效果,預設是‘swing’,可用參數‘liear’
  • fn:回調函數,在動畫完成時執行的函數,每個元素執行一次

4.漸進方式調整到指定的不透明度:fadeTo(speed,opacity,easeing,fn)

注意:

  • opacity透明度必須寫,取值0-1之間。
  • speed:三種預定速度之一的字元串(‘show’,‘normal’,or’fast’)或表示動畫時長的毫秒數值(如:1000),必須要寫。
  • easeing:用來指定切換效果,預設是‘swing’,可用參數‘liear’
  • fn:回調函數,在動畫完成時執行的函數,每個元素執行一次
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
		<style>
			div{
				width:200px;
				height:300px;
				background-color: pink;
				display:none;
			}
		</style>
	</head>
	<body>
		<button>淡入效果</button>
		<button>淡出效果</button>
		<button>淡入淡出效果</button>
		<button>修改透明度</button>
		<div></div>
		<script>
			$(function(){
				//淡入效果fadeIn()
				$("button").eq(0).click(function(){
					$("div").fadeIn(1000);
				})
				//淡出效果fadeOut()
				$("button").eq(1).click(function(){
					$("div").fadeOut(1000);
				})
				//淡入淡出效果fadeToggle()
				$("button").eq(2).click(function(){
					$("div").fadeToggle(1000);
				})
				//修改透明度fadeTo(),時間和速度必須要寫
				$("button").eq(3).click(function(){
					$("div").fadeTo(1000,0.5);
				})
			})
		</script>
	</body>
</html>

           
jQuery筆記jQuery筆記
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
		<style>
			*{
				padding:0;
				margin:0;
			}
			li{
				list-style: none;
			}
			ul{
				padding:4px;
				width:612px;
				height:308px;
				margin:100px auto;
				background-color: #000;
			}
			ul li{
				width:200px;
				height:150px;
				float: left;
				margin:2px;
			}
			ul img{
				width:200px;
				height:150px;
				
			}
		</style>
	</head>
	<body>
		<div class="wrap">
			<ul>
				<li><img src="img/冬裙.png"/></li>
				<li><img src="img/冬靴.png"/></li>
				<li><img src="img/雪地靴.png"/></li>
				<li><img src="img/羽絨服.png"/></li>
				<li><img src="img/女褲.png"/></li>
				<li><img src="img/棉服.png"/></li>
			</ul>
		</div>
		<script>
			$(function(){
				$("ul li").hover(function(){
					//滑鼠移入的時候,其他的li的透明度為0.5
					$(this).siblings().stop().fadeTo(400,0.5)
				},function(){
					//滑鼠移出的時候,其他的li的透明度為1
					$(this).siblings().stop().fadeTo(400,1)
				})
			})
		</script>
	</body>
</html>
           

3-6 自定義動畫animate

文法:animate(params,[speed],[easing],[fn])

參數:

  • params:想要更改的樣式屬性,以對象形式傳遞,必須要。屬性名可以不用帶引号,如果是複合屬性則需要采用駝峰命名法borderleft。其餘參數可以省略。
  • speed:三種預定速度之一的字元串(‘show’,‘normal’,or’fast’)或表示動畫時長的毫秒數值(如:1000),必須要寫。
  • easeing:用來指定切換效果,預設是‘swing’,可用參數‘liear’
  • fn:回調函數,在動畫完成時執行的函數,每個元素執行一次
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" ></script>
		<style>
			div{
				position: absolute;
				width:200px;
				height:200px;
				background-color: pink;
			}
		</style>
	</head>
	<body>
		<button>動起來</button>
		<div></div>
		<script>
			$("button").click(function(){
				$("div").animate({
					left:500,
					top:300,
					width:500,
					opacity:0.3
				},500)
			})
		</script>
	</body>
</html>

           
jQuery筆記jQuery筆記

案例分析:

  • 滑鼠經過某個小li有兩步操作
  • 目前小li寬度變為224px,同時裡面的小圖檔淡出,大圖檔淡入
  • 其餘兄弟小li寬度變為69px,小圖檔淡入,大圖檔淡出
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" ></script>
		<style type="text/css">
	        * {
	            margin: 0;
	            padding: 0;
	        }
	        
	        img {
	        	display: block;
	        }
	        
	        ul {
	            list-style: none;
	        }
	        
	        .king {
	            width: 852px;
	            margin: 100px auto;
	            background: pink;
	            overflow: hidden;
	            padding: 10px;
	        }
	        
	        .king ul {
	            overflow: hidden;
	        }
	        
	        .king li {
	            position: relative;
	            float: left;
	            width: 69px;
	            height: 69px;
	            margin-right: 10px;
	        }
	        
	        .king li.current {
	            width: 224px;
	        }
	        
	        .king li.current .big {
	            display: block;
	        }
	        
	        .king li.current .small {
	            display: none;
	        }
	        
	        .big {
	            width: 224px;
	            display: none;
	        }
	        
	        .small {
	            position: absolute;
	            top: 0;
	            left: 0;
	            width: 69px;
	            height: 69px;
	            border-radius: 5px;
	        }
    </style>
	</head>
	<body>
		<div class="king">
			<ul>
				<li class="current">
					<a href="#">
						<img src="img/a1.png" class="small"/> 
						<img src="img/a2.png" class="big"/> 
					</a>
				</li>
				<li>
					<a href="#">
						<img src="img/b1.png" class="small"/> 
						<img src="img/b2.png" class="big"/> 
					</a>
				</li>
				<li>
					<a href="#">
						<img src="img/c1.png" class="small"/> 
						<img src="img/c2.png" class="big"/> 
					</a>
				</li>
				<li>
					<a href="#">
						<img src="img/d1.png" class="small"/> 
						<img src="img/d2.png" class="big"/> 
					</a>
				</li>
				<li>
					<a href="#">
						<img src="img/e1.png" class="small"/> 
						<img src="img/e2.png" class="big"/> 
					</a>
				</li>
				<li>
					<a href="#">
						<img src="img/f1.png" class="small"/> 
						<img src="img/f2.png" class="big"/> 
					</a>
				</li>
				<li>
					<a href="#">
						<img src="img/g1.png" class="small"/> 
						<img src="img/g2.png" class="big"/> 
					</a>
				</li>
			</ul>
		</div>
		<script>
			$(function(){
				$(".king li").mouseenter(function(){
					$(this).stop().animate({
						width:224
					}).find(".small").stop().fadeOut().siblings(".big").stop().fadeIn();
					$(this).siblings("li").stop().animate({
						width:69
					}).find(".small").stop().fadeIn().siblings(".big").stop().fadeOut();
				})
			})
		</script>
	</body>
</html>
           

4、jQuery屬性操作

4-1 設定或擷取元素固有屬性值 prop()

所謂元素固有屬性就是元素本身自帶的屬性,比如元素裡面的href,比如input裡面的type。

  • 擷取屬性文法 prop(“屬性”)
  • 設定屬性文法 prop(“屬性”,“屬性值”)

4-2 設定或擷取元素自定義屬性值 attr()

使用者自己給元素添加的屬性,我們成為自定義屬性。比如div添加index=“1”

  • 擷取屬性文法 attr(“屬性”) //類似原生getAttribute()
  • 設定屬性文法 attr(“屬性”,“屬性值”) //類似原生setAttribute()

該方法也可以擷取h5自定義屬性

4-3 資料緩存 data()

data()方法可以在指定的元素上存取資料,并不會修改dom元素結構。一旦頁面重新整理,之前存放的資料都将被移除。

  • 附加資料文法 data(“name”,“value”) //向被選元素附加資料
  • 擷取資料文法 data(“name”) //向被選元素擷取資料

同時,還可以讀取html5自定義屬性data-index,得到的是數字型。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js" ></script>
	</head>
	<body>
		<a href="http://www.baidu.com" title="你好">都挺好</a>
		<input type="checkbox" checked/>
		<div data-index="1">我是div</div>
		<span>123</span>
		<script>
			$(function(){
				//1.element.pro("屬性名"),擷取固有的屬性方法
				console.log($("a").prop("href"));
				console.log($("a").prop("title"));
				//設定屬性
				//$("a").prop("title","都挺好");
				$("input").change(function(){
					console.log($(this).prop("checked"))
				})
				//2.擷取自定義的屬性  attr()
				console.log($("div").attr("data-index"));
				$("div").attr("index",4)
				//3.資料緩存data() 這裡面的資料是存放在元素的記憶體裡面
				$("span").data("uname","andy");
				console.log($("span").data("uname"));
				//這個方法和data-index h5自定義屬性 第一個 不用寫data- 而且傳回的是數字型
				console.log($("div").data("index"));
			})
		</script>
	</body>
</html>

           

5、jQuery文本屬性值

主要針對元素的内容還有表單的值操作。

  • 普通元素内容html() (相當于原生的innerHTML)
    html()//擷取元素的内容
    html("内容")//設定元素的内容
               
  • 普通元素文本内容text() (相當于與原生innerText)
    text() //擷取元素的文本内容
    text("文本内容) //設定元素的文本内容
               
  • 表單的值 val() (相當于原生value)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
	</head>
	<body>
		<div>
			<span>我是内容</span>
		</div>
		<input type="text" value="請輸入内容">
		<script>
			$(function(){
				//擷取設定元素内容 html()
				console.log($("div").html());
				/*$("div").html("<p>123</p>")*/
				//擷取設定元素文本内容 text()
				console.log($("div").text());
				$("div").text("123")
				//擷取設定表單值  val()
				console.log($("input").val());
				$("input").val("123");
			})
		</script>
	</body>
</html>
           

追加知識點:傳回祖先元素方法 parents()

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
	</head>
	<body>
		<div class="one">
			<div class="two">
				<div class="three">
					<div class="four">
						我不容易
					</div>
				</div>
			</div>
		</div>
		<script>
			var one=$(".four").parent().parent().parent();
			//利用parents()查找上級
			var one=$(".four").parents();//parents()括号裡為空傳回的是他所有的上級
			//parents(選擇器)是查找的某一個上級
			var one=$(".four").parents(".one");
			console.log(one);
		</script>
	</body>
</html>

           

6、jQuery元素操作

主要是周遊、建立、添加、删除元素操作。

6-1 周遊元素

jquery隐式疊代是對同一類元素做了同樣的操作。如果想要給同一類元素做不同操作,就需要用到周遊。

文法1:

$("div).each(function(index,domEle){...})
           

1.each()方法周遊比對的每一個元素。主要用dom處理。each每一個

2.裡面的回調函數有2個參數:index是每個元素的索引号;domele是每個dom元素對象,不是jquery對象。

3.是以要想使用jquery方法,需要給這個dom元素轉換為juqery對象 $(domEle)

文法2:

$.each(object,function(index,element){....})
           

1.$.each()方法可用于周遊任何對象。主要用于資料處理,比如數組,對象

2.裡面的函數有2個參數:index是每個元素的索引号;element周遊内容

這兩個文法的代碼驗證

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
	</head>
	<body>
		<div>1</div>
		<div>2</div>
		<div>3</div>
		<script>
			$(function(){
				var sum=0;
				//$("div").css("color","pink");
				//如果針對于同一類元素做不同的操作,需要用到周遊元素(類似for,但是比for更強大)
				var arr=["pink","red","blue"]
				//1.each()方法
				$("div").each(function(index,domEle){
					//回調函數第一個參數一定是索引号,可以自己指定索引号名稱
					/*console.log(index);
					 * 回調函數第二個參數一定是dom元素對象,要使用jueqry方法要轉換成jquery對象
					console.log(domEle);*/
					$(domEle).css("color",arr[index]);
					sum=sum+parseInt($(domEle).text());
				})
				console.log(sum);
				//2.$.each()方法周遊元素,主要用于周遊資料,處理資料
				/*$.each($("div"),function(i,ele){
					console.log(i);
					console.log(ele);
				})*/
				/*$.each(arr,function(i,ele){
					console.log(i);
					console.log(ele);
				})*/
				$.each({
					name:"andy",
					age:18
				},function(i,ele){
					console.log(i);//輸出的是name age屬性名
					console.log(ele);//輸出的是andy 18屬性值
				})
			})
			
		</script>
	</body>
</html>
           

6-2 建立元素

文法:

$('<li></li>')

動态的建立了一個li

6-3 添加元素

内部添加

  • element.append(“内容”)

    把内容放入比對元素内部最後面,類似原生appendChild。

  • element.prepend(“内容”)

    把内容放入比對元素内部最前面,類似原生insertBefore。

外部添加

element.after("内容");//把内容放入目标元素後面
element.before("内容");//把内容放入目标元素前面
           

注意:内部添加元素,生成之後,他們是父子關系;外部添加元素,生成之後,他們是兄弟關系。

6-4 删除元素

element.remove();//删除比對的元素(本身)
element.empty();//删除比對的元素集合中所有的子節點
element.html("");//清空比對的元素内容
           

建立、添加、删除知識的代碼驗證

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
	</head>
	<body>
		<ul>
			<li>原來的li</li>
		</ul>
		<div class="text">我是原來的div</div>
		<script>
			$(function(){
				//1.建立元素
				var li=$("<li>我是後來建立的li</li>")
				//2.添加元素
				//(1)内部添加
				//$("ul").append(li);//element.append()是内部添加并且追加到内容的最後面
				$("ul").prepend(li)//element.prepend()是内部添加到内容的最前面
				//(2)外部添加
				var div=$("<div>我是後來添加的div</div>");
				//$(".text").after(div);//after()在指定的元素後面添加元素
				$(".text").before(div);//before()在指定的元素前面添加元素
				//删除元素
				//$("ul").remove();//删除元素本身
				$("ul").empty();//删除元素的所有子節點
				$("ul").html("");//删除該元素的所有内容
			})
		</script>
	</body>
</html>
           

6-5 購物車綜合案例

知識點包括:屬性操作、文本屬性、元素操作等

jQuery筆記jQuery筆記
<head>
    <meta charset="UTF-8">
    <title>我的購物車-品優購</title>
    <!-- 引入公共樣式的css 檔案 -->
    <link rel="stylesheet" href="index.css">
    <!-- 先引入jquery  -->
    <script src="../js/jquery.min.js"></script>
    <!-- 在引入我們自己的js檔案 -->
    <script src="index.js"></script>
</head>
<body>
    <div class="c-container">
        <div class="w">
            <div class="cart-filter-bar">
                <em>全部商品</em>
            </div>
            <!-- 購物車主要核心區域 -->
            <div class="cart-warp">
                <!-- 頭部全選子產品 -->
                <div class="cart-thead">
                    <div class="t-checkbox" >
                        <input type="checkbox" name="" id="" class="checkall"> 全選
                    </div>
                    <div class="t-goods" >商品</div>
                    <div class="t-price" >單價</div>
                    <div class="t-num">數量</div>
                    <div class="t-sum" >小計</div>
                    <div class="t-action">操作</div>
                </div>
                <!-- 商品詳細子產品 -->
                <div class="cart-item-list">
                    <div class="cart-item check-cart-item">
                        <div class="p-checkbox">
                            <input type="checkbox" name="" id="" checked class="j-checkbox">
                        </div>
                        <div class="p-goods">
                            <div class="p-img">
                                <img src="img/p1.png" alt="">
                            </div>
                            <div class="p-msg">【5本26.8元】經典兒童文學彩圖青少版八十天環遊地球中學生							國文教學大綱
                            </div>
                        </div>
                        <div class="p-price">¥12.60</div>
                        <div class="p-num">
                            <div class="quantity-form">
                                <a href="javascript:;" class="decrement">-</a>
                                <input type="text" class="itxt" value="1">
                                <a href="javascript:;" class="increment">+</a>
                            </div>
                        </div>
                        <div class="p-sum">¥12.60</div>
                        <div class="p-action"><a href="javascript:;">删除</a></div>
                    </div>
                    <div class="cart-item">
                        <div class="p-checkbox">
                            <input type="checkbox" name="" id="" class="j-checkbox">
                        </div>
                        <div class="p-goods">
                            <div class="p-img">
                                <img src="img/p2.png" alt="">
                            </div>
                            <div class="p-msg">【2000張貼紙】貼紙書 3-6歲 貼畫兒童 貼畫書全套12冊 貼畫 貼紙兒童 汽</div>
                        </div>
                        <div class="p-price">¥24.80</div>
                        <div class="p-num">
                            <div class="quantity-form">
                                <a href="javascript:;" class="decrement">-</a>
                                <input type="text" class="itxt" value="1">
                                <a href="javascript:;" class="increment">+</a>
                            </div>
                        </div>
                        <div class="p-sum">¥24.80</div>
                        <div class="p-action"><a href="javascript:;">删除</a></div>
                    </div>
                    <div class="cart-item">
                        <div class="p-checkbox">
                            <input type="checkbox" name="" id="" class="j-checkbox">
                        </div>
                        <div class="p-goods">
                            <div class="p-img">
                                <img src="img/p3.png" alt="">
                            </div>
                            <div class="p-msg">唐詩三百首+成語故事全2冊 一年級課外書 精裝注音兒童版 國小生二三年級課外閱讀書籍</div>
                        </div>
                        <div class="p-price">¥29.80</div>
                        <div class="p-num">
                            <div class="quantity-form">
                                <a href="javascript:;" class="decrement">-</a>
                                <input type="text" class="itxt" value="1">
                                <a href="javascript:;" class="increment">+</a>
                            </div>
                        </div>
                        <div class="p-sum">¥29.80</div>
                        <div class="p-action"><a href="javascript:;">删除</a></div>
                    </div>
                </div>

                <!-- 結算子產品 -->
                <div class="cart-floatbar">
                    <div class="select-all">
                        <input type="checkbox" name="" id="" class="checkall">全選
                    </div>
                    <div class="operation">
                        <a href="javascript:;" class="remove-batch"> 删除選中的商品</a>
                        <a href="javascript:;" class="clear-all">清理購物車</a>
                    </div>
                    <div class="toolbar-right">
                        <div class="amount-sum">已經選<em>1</em>件商品</div>
                        <div class="price-sum">總價: <em>¥12.60</em></div>
                        <div class="btn-area">去結算</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
附:css
*{
	padding:0;
	margin:0;
}
a{
	text-decoration: none;
	color:#000;
}
.w{
	width:1200px;
	margin:0 auto;
}
.check-cart-item{
	background-color: papayawhip;
}
.w em{
	color:red;
	font-style:normal;
	font-size:20px;
	border-bottom: 3px solid red;
}
.cart-thead{
	margin-top:3px;
	padding-left:20px;
	height:50px;
	background-color: rgba(0,0,0,0.2);
	line-height: 50px;
}
.cart-thead div{
	float: left;
	margin-right:100px;
}
.cart-thead .t-price{
	margin-right:90px
}
.cart-thead .t-num{
	margin-right:146px
}
.cart-thead .t-goods{
	margin-right:400px;
}
.cart-item{
	margin-top:10px;
	height:200px;
	border-top:3px solid #ccc;
	padding:10px;
	border-left:1px solid #ccc;
	border-right:1px solid #ccc;
	border-bottom:1px solid #ccc;
}

.cart-item div{
	float: left;
	margin-right:60px;
}

.cart-item .p-checkbox{
	margin-right:100px;
}
.cart-item .p-goods{
	width:400px;
	position: relative;
}
.p-goods{
	position: relative;
}
.p-img{
	width:80px;
	height:80px;
	border:1px solid #ccc;
	background-color:#fff;
	text-align: center;
	line-height: 60px;
}
.p-goods img{
	width:70px;
	height:70px;
	
}
.p-goods .p-msg{
	position: relative;
	right:-86px;
	top:-82px;
}
.quantity-form{
	padding: 0 3px;
	border:1px solid #ccc;
	height:30px;
	background-color: #fff;
}
.p-num input{
	border:0;
	width:32px;
	height:30px;
	border-left:1px solid #ccc;
	border-right:1px solid #ccc;
	text-align: center;
}
.p-action{
	padding-left:28px;
}
.cart-floatbar{
	margin:10px 0;
	height:50px;
	border:1px solid #ccc;
	line-height: 50px;
}
.cart-floatbar div{
	float: left;
}
.select-all{
	margin-left:10px;
	margin-right:50px;
}
.operation{
	margin-right:400px;
}
.operation a{
	margin:8px;
}
.cart-floatbar .toolbar-right{
	float: right;
}
.toolbar-right em{
	border:0;
}
.amount-sum em{
	margin:0 5px;
}
.btn-area{
	width:100px;
	height:50px;
	background-color: red;
	color:#fff;
	text-align: center;
}
.price-sum{
	margin:0 20px;
}

附:js
$(function(){
	//1.全選和全不選
	//就是把全選(checkall)的狀态指派給三個小的按鈕(j-checkbox)就可以了
	$(".checkall").change(function(){
		//console.log($(this).prop("checked"))
		$(".j-checkbox,.checkall").prop("checked",$(this).prop("checked"));
		if($(this).prop("checked")){
			//讓所有的商品都操作check-cart-item類名增加
			$(".cart-item").addClass("check-cart-item");
		}else{
			//check-cart-item類名删除
			$(".cart-item").removeClass("check-cart-item");
		}
	})
	//2.如果小複選框被選中的個數等于3,就應該把全選按鈕選上,否則全選按鈕不選。
	$(".j-checkbox").change(function(){
		/*if(被選中的小複選框的個數等于3){
			就要選中全選按鈕
		}else{
			不要選中全選按鈕
		}*/
		//console.log($(".j-checkbox:checked").length);
		//$(".j-checkbox").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");
		}
	})
	//3增減商品數量子產品,首先聲明一個變量,當我們點選+号(increment),就讓這個值++,然後指派給文本框
	$(".increment").click(function(){
		//得到目前兄弟文本框的值
		var n=$(this).siblings(".itxt").val();
		n++;
		$(this).siblings(".itxt").val(n);
		//4.每次點選+号或者-号,根據文本框的值乘以目前商品的價格就是商品的小計
		var p=$(this).parents(".p-num").siblings(".p-price").html();
		p=p.substr(1);
		console.log(p);
		//toFixed(2) 保留兩位小數
		var price=(p*n).toFixed(2);
		$(this).parents(".p-num").siblings(".p-sum").html("¥"+price);
		getSum();
	})
	$(".decrement").click(function(){
		//得到目前兄弟文本框的值
		var n=$(this).siblings(".itxt").val();
		if(n==1){
			return false;
		}
		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);
		$(this).parents(".p-num").siblings(".p-sum").html("¥"+price);
		getSum();
	})
	//4.使用者修改文本框的值,計算小計子產品
	$(".itxt").change(function(){
		var n=$(this).val();
		var p=$(this).parents(".p-num").siblings(".p-price").html();
		p=p.substr(1);//把¥去掉
		$(this).parents(".p-num").siblings(".p-sum").html("¥"+(p*n).toFixed(2));
		getSum();
	})
	getSum();
	//5.總計和總額
	function getSum(){
		//總的數量count
		var count=0;
		//總的錢數money
		var money=0;
		$(".itxt").each(function(i,ele){
			count=count+parseInt($(ele).val());
		})
		$(".amount-sum em").text(count);
		$(".p-sum").each(function(i,ele){
			money+=parseFloat($(ele).text().substr(1));
		})
		$(".price-sum em").text("¥"+money.toFixed(2))
	}
	//6.删除商品子產品
	//商品後面的删除按鈕
	$(".p-action a").click(function(){
		$(this).parents(".cart-item").remove();
		getSum();
	})
	//删除選中的商品
	$(".remove-batch").click(function(){
		//console.log($(".j-checkbox:checked"));//被選中的小複選框
		$(".j-checkbox:checked").parents(".cart-item").remove();
		getSum();
	})
	//清空購物車
	$(".clear-all").click(function(){
		$(".cart-item").remove();
		getSum();
	})
})
           

7、jQuery尺寸、位置操作

7-1 jquery尺寸

文法 用法
width() /height() 取得比對元素寬度和高度值,隻算width/height
innerWidth()/innerHeight() 取得比對元素寬度和高度值,包含padding
outerWidth()/outerHeight() 取得比對元素寬度和高度值,包含padding、border
outerWidth(true)/outerHeight(true) 取得比對元素寬度和高度值,包含padding、border、margin
  • 以上參數為空,則是擷取相應值,傳回的是數字型。
  • 如果參數為數字,則是修改相應值。
  • 參數可以不必寫機關
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
		<style>
			div{
				width:200px;
				height:200px;
				background-color: pink;
				padding:10px;
				border:1px solid red;
				margin:20px;
			}
		</style>
	</head>
	<body>
		<div></div>
		<script>
			$(function(){
				//擷取值
				console.log($("div").width());//200
				//設定值
				//$("div").width(300);
				console.log($("div").innerWidth());//220包含padding
				console.log($("div").outerWidth());//222包含padding、border
				console.log($("div").outerWidth(true));//262包括padding、border、margin
			})
		</script>
	</body>
</html>
           

7-2 jquery位置

位置主要有三個:offset()、position()、scrollTop()/scrollHeight

1.offset()設定或擷取元素偏移

  • offset()方法或傳回被選元素相對于文檔的偏移坐标,跟父級沒有關系。
  • 該方法有2個屬性left、top。offset().top用于擷取距離文檔頂部的距離,offset().left()用于擷取文檔左側的距離。
  • 可以設定元素的偏移: offset({top:200,left:200})

2.position()擷取距離帶有定位父級元素(偏移)

  • 如果沒有定位,則以文檔為準
  • 不能設定内容
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery.min.js"></script>
		<style>
			*{
				padding:0;
				margin: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>
	</head>
	<body>
		<div class="father">
			<div class="son"></div>
		</div>
		<script>
			$(function(){
				//1.擷取設定距離文檔的位置(偏移)offset()
				console.log($(".son").offset());//傳回的是一個對象,裡面包含top和left值
				console.log($(".son").offset().top);//傳回100的top值
				/*$(".son").offset({
					top:200,
					left:200
				})*///和父親盒子沒有關系,就算加了定位也沒關系,是相對于文檔。
				//2.擷取距離帶有定位父級元素(偏移),注意:不能設定  position() 如果沒有定位,則以文檔為準
				console.log($(".son").position());//傳回的都是10
				console.log($(".son").position().top);//10
			})
		</script>
	</body>
</html>
           

3.scrollTop()/scrollHeight() 設定或擷取元素被卷去的頭部和左側

jQuery筆記jQuery筆記
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
		<style>
			*{
				padding:0;
				margin:0;
			}
			body{
				height:2000px;
			}
			.container{
				width:900px;
				margin:400px auto;
				height:500px;
				background-color: skyblue;
			}
			.back{
				width:50px;
				height:50px;
				background-color: pink;
				position: fixed;
				bottom:100px;
				right:30px;
				display: none;
			}
		</style>
	</head>
	<body>
		<div class="back">傳回頂部</div>
		<div class="container"></div>
		<script>
			$(function(){
				//$(document).scrollTop(100);//指派操作
				//scrollTop()
				//$(window).scroll() 頁面滾動事件
				var boxTop=$(".container").offset().top;
				console.log(boxTop)
				$(window).scroll(function(){
					if($(document).scrollTop()>=boxTop){
						$(".back").fadeIn()
					}else{
						$(".back").fadeOut()
					}
				})
				//傳回頂部
				$(".back").click(function(){
					//$(document).scrollTop(0)
					/*$(document).stop().animate({
						scrollTop:0
					})*///不能是文檔,而是html和body做動畫
                    //animate()裡面有個scrollTop屬性
					$("body,html").stop().animate({
						scrollTop:0
					})
				})
			})
		</script>
	</body>
</html>
           

7-3 電梯導航案例

jQuery筆記jQuery筆記
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			*{
				padding: 0;
				margin: 0;
			}
			body{
				height:3000px;
			}
			.w{
				width:1200px;
				margin: 10px auto;
			}
			.sj{
				height:300px;
				background-color: pink;
			}
			.tj{
				height:200px;
				background-color: burlywood;
				margin-top:5px;
			}
			.dq{
				height:300px;
				background-color: skyblue;
			}
			.hfmz{
				height:400px;
				background-color: bisque;
			}
			.rsbh{
				height:300px;
				background-color: rosybrown;
			}
			.fz{
				height:500px;
				background-color: burlywood;
			}
			.xz{
				height:400px;
				background-color: yellowgreen;
			}
			.fixedtool{
				width:60px;
				height:300px;
				background-color: palevioletred;
				font-size:14px;
				position: fixed;
				top:200px;
				left:11px;
				display: none;
			}
			ul li{
				text-align: center;
				list-style: none;
				width:100%;
				height:50px;
				line-height: 50px;
				color:#000;
			}
			.current{
				background-color: darkred;
				color:#fff;	
			}
		</style>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
	</head>
	<body>
		<div class="container">
			<div class="head w">
				<div class="sj">手機通訊</div>
				<div class="tj">今日推薦</div>
			</div>
			<div class="dq w">家用電器</div>
			<div class="hfmz w">護膚美妝</div>
			<div class="rsbh w">日常百貨</div>
			<div class="fz w">服裝</div>
			<div class="xz w">男女鞋子</div>
		</div>
		
		<div class="fixedtool">
			<ul>
				<li class="current">手機通訊</li>
				<li>家用電器</li>
				<li>護膚美妝</li>
				<li>日常百貨</li>
				<li>服裝</li>
				<li>男女鞋子</li>
			</ul>
		</div>
		<script>
			//console.log($(".container>div").eq(0))
			$(function(){
				//當我們點選了小li 此時不需要執行頁面滾動事件裡面的li的背景選擇添加類名current,可以使用節流閥(互斥鎖)
				var flag=true;
				//1.當頁面滾動到今日推薦,電梯導航欄就顯示出來
				var tjTop=$(".tj").offset().top;
				toggleTool();
				function toggleTool(){
					if($(document).scrollTop()>=tjTop){
						$(".fixedtool").fadeIn();
					}else{
						$(".fixedtool").fadeOut();
					}
				}
				$(window).scroll(function(){
					toggleTool();
					//3.頁面滾動到某個内容區域,左側電梯導肮小li相應添加和删除current類名
					if(flag){
						$(".container .w").each(function(i,ele){
							if($(document).scrollTop() >= $(ele).offset().top){
								$(".fixedtool li").eq(i).addClass("current").siblings().removeClass("current")
							}
						})
					}
				})
				//2.點選電梯導航顯示相應的内容
				$(".fixedtool li").click(function(){
					flag=false;
					//當我們每次點選小li,就需要計算出頁面要去往的位置
					//旋選出對應索引号的内容區的盒子,計算它的offset().top
					var index=$(this).index();
					var top=$(".container .w").eq(index).offset().top;
					//頁面動畫滾動效果
					$("body,html").stop().animate({
						scrollTop:top
					},function(){
						flag=true;
					})
					//點選之後,讓目前的小li加上類名current,其他兄弟移除類名
					$(this).addClass("current").siblings("li").removeClass("current")
				})
			})
		</script>
	</body>
</html>
           

三、 jquery事件

目标:

  • 能夠說出四種常見的注冊事件
  • 能夠說出on綁定事件的優勢
  • 能夠說出jquery事件委派的優點以及方式
  • 能夠說出綁定事件與解綁事件

1、 jquery事件注冊

單個事件注冊

文法:

elelment.事件(function(){})
$('div').click(function(){事件處理程式})
           

其他事件和原生基本一緻,比如:mouseover、mouseout、blur、focus、change、keydown、keyup、resize、scroll等

2、 jquery事件處理

2-1 事件處理 on()綁定事件

on方法在比對元素上綁定一個或者多個事件的事件處理函數

文法:element.on(events,[selector],fn)

  • events:一個或者多個空格分隔的事件類型,如‘click’或‘keydown’。
  • [selector]:元素的子元素選擇器
  • fn:回調函數即綁定在元素身上的偵聽函數

on()方法優勢1:

可以綁定多個事件,多個處理事件處理程式。

$("div").on({
	mouseover:function(){},
	mouseout:function(){},
	click:function(){}
})
//如果事件處理程式相同
$('div').on('mouseover mouseout',function(){
	$(this).toggleClass('current')
})
           

on()方法優勢2:

可以事件委派操作。事件委派的定義就是把原來加給子元素身上的事件綁定在父元素身上,就是把事件委派給父元素。

$('ul').on('click','li',function(){
	alert(11)
})
           

在此之前有bind(),live(),delegate()等方法來處理事件綁定或者事件委派,最新版本是用on替代他們。

on()方法優勢3:

動态建立的元素,click()沒有辦法綁定事件,on()可以給動态生成的元素綁定事件。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
		<style>
			div{
				width:100px;
				height:100px;
				background-color: pink;
			}
			.current{
				background-color: purple;
			}
		</style>
	</head>
	<body>
		<div></div>
		<ul>
			<li>我們都是好孩子</li>
			<li>我們都是好孩子</li>
			<li>我們都是好孩子</li>
			<li>我們都是好孩子</li>
			<li>我們都是好孩子</li>
		</ul>
		<ol>
			
		</ol>
		<script>
			$(function(){
				//1.單個事件注冊
				/*$("div").click(function(){
					$(this).css("background","blue")
				})
				$("div").mouseenter(function(){
					$(this).css("background","red")
				})
				
				*/
				//2.事件處理on
				/*$("div").on({
					mouseenter:function(){
						$(this).css("background","red")
					},
					click:function(){
						$(this).css("background","purple")
					},
					mouseleave:function(){
						$(this).css("background","blue")
					}
				});*/
				$("div").on("mouseenter mouseleave",function(){
					$(this).toggleClass("current")
				});
				//(1)on可以實作事件委派
				$("ul li").click()
				$("ul").on("click","li",function(){
					alert(11)
				})
				//click綁定在ul上,但是觸發的對象是ul的li
				
				//(2)on可以給未來動态建立的元素綁定事件
				/*$("ol li").click(function(){
					alert(22);
				})*/
				$("ol").on("click","li",function(){
					alert(22);
				});
				var li=$("<li>我是未來建立的</li>")
				$("ol").append(li);
			})
		</script>
	</body>
</html>

           
jQuery筆記jQuery筆記
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
		<style>
			*{
				padding:0;
				margin:0;
			}
			li{
				list-style: none;
			}
			a{
				text-decoration: none;
			}
			.box{
				width:500px;
				margin:100px auto;
				padding:10px;
				box-sizing: border-box;
				border: 1px solid #000;
			}
			.text{
				width:370px;
				height:100px;
				resize:none;
				outline: none;
			}
			ul{
				margin-top:10px;
				width:200px;
				margin-left:68px;
			}
			ul li{
				width:370px;
				height:26px;
				border-bottom: 1px dashed #ccc;
				line-height:26px;
			}
			ul li a{
				float: right;
			}
		</style>
	</head>
	<body>
		<div class="box" id="weibo">
			<span>微網誌釋出</span>
			<textarea class="text"></textarea>
			<button>釋出</button>
			<ul>
			</ul>
		</div>
		<script>
			$(function(){
				//點選釋出按鈕,動态建立一個li,放入文本框的内容和删除按鈕,并且添加到ul中
				$("button").on("click",function(){
					var li=$("<li></li>")
					li.html($(".text").val()+"<a href='javascript:;'>删除</a>")
					$("ul").prepend(li);
					li.slideDown();
					$(".text").val("");
					
				})
				//2.點選的删除按鈕,可以删除目前的微網誌留言li
				/*$("ul li a").click(function(){//此時的click不能給動态建立的a添加事件
						$(this).parent().remove();
					})*/
				//on可以給動态建立的元素綁定事件
				$("ul").on("click","a",function(){
						$(this).parent().slideUp(function(){
							$(this).remove();
						});
					})
			})
		</script>
	</body>
</html>

           

2-2 事件處理 off()解綁事件

off()方法可以移除通過on()方法添加的事件處理程式。

補充知識:元素.one() 隻能觸發一次

$('p').off();//解綁p元素所有事件處理程式
$('p').off('click');//解綁p元素上面的點選事件
$('ul').off('click','li');//解除事件委托
           
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
		<style>
			div{
				width:100px;
				height:100px;
				background-color: pink;
			}
		</style>
	</head>
	<body>
		<div></div>
		<ul>
			<li>我們都是好孩子</li>
			<li>我們都是好孩子</li>
			<li>我們都是好孩子</li>
		</ul>
		<p>我是p</p>
		<script>
			$(function(){
				$("div").on({
					click:function(){
						console.log("我點選了")
					},
					mouseenter:function(){
						console.log("滑鼠經過了")
					}
				})
				//事件委托
				$("ul").on("click","li",function(){
					alert(11);
				})
				//1.事件解綁 off()
				//$("div").off();//解除元素身上所有的事件
				$("div").off("click");//解除元素身上click的事件
				//解除事件委托
				$("ul").off("click","li");
				//2. one() 隻能觸發一次
				$("p").one("click",function(){
					alert(11)
				})
			})
			
		</script>
	</body>
</html>

           

2-3 自動觸發事件 trigger()

有些事件希望是自動觸發,比如輪播圖自動播放功能和右鍵按鈕一緻。可以利用定時器自動觸發右側按鈕點選事件,不必滑鼠事件點選觸發。

element.click();//第一種簡寫方式
element.trigger('type');//第二種自動觸發模式
$('p').on('click',function(){
	alert(11);
})
$('p').trigger("click);//此時自動觸發點選事件,不需要滑鼠點選
element.triggerHandler(type)/;/第三種自動觸發模式
//他與前兩種最大的差別就是不會觸發預設行為
           
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			div{
				width:100px;
				height:100px;
				background-color: pink;
			}
		</style>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
		<script>
			$(function(){
				$("div").on("click",function(){
					alert(11);
				})
				//自動觸發事件
				//1.element.click()
				//$("div").click();
				
				//2.element.trigger(type)
				//$("div").trigger("click")
				
				//3.element.triggerHandler(type)  他與前兩種最大的差別就是不會觸發預設行為
				//$("div").triggerHandler("click")
				$("input").on("focus",function(){
					$(this).val("你好嗎")
				})
				//$("input").triggerHandler("focus") 沒有光标
				$("input").trigger("focus");//有光标
			})
		</script>
	</head>
	<body>
		<div></div>
		<input type="text">
	</body>
</html>

           

3、jquery事件對象

事件被觸發,就會有事件對象的産生。

element.on(events,[selector],function(evet){})
           

阻止預設行為:event.preventDefault() 或者return false

阻止冒泡: event.stopPropagation()

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			div{
				width:100px;
				height:100px;
				background-color: pink;
			}
		</style>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
		<script>
			$(function(){
				$(document).on("click",function(){
					alert("點選了document")
				})
				$("div").on("click",function(e){
					/*console.log(e)*/
					alert("點選了div");
					//組織冒泡行為
					e.stopPropagation();
				})
			})
		</script>
	</head>
	<body>
		<div></div>
		
	</body>
</html>
           

四、 jquery 其他方法

目标:

  • 能夠說出jquery對象的拷貝方法
  • 能夠說出jquery多庫共存的兩種方法
  • 能夠使用jquery插件

1、jquery拷貝對象

如果想要把某個對象拷貝給另外一個對象,此時可以使用$.exend()方法。

文法: $.exend([deep],target,object1,objectN)

  • deep:如果設為true為深拷貝,預設為false淺拷貝
  • target:要拷貝的目标對象
  • object1:待拷貝到第一個對象的對象。
  • objectN:待拷貝到第N個對象的對象。
  • 淺拷貝是把被拷貝的對象複雜資料類型中的位址拷貝給目标對象,修改目标對象會影響被拷貝的對象。
  • 深拷貝,前面加true,完全克隆(拷貝的對象,而不是位址),修改目标對象不會影響到被拷貝的對象。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery.min.js"></script>
		<script>
			$(function(){
				/*var targetObj={};
				var obj={
					id:1,
					name:"andy"
				}
				//$.extend(taget,obj)
				$.extend(targetObj,obj);
				console.log(targetObj);*/
				
				/*var targetObj={
					id:0
				};
				var obj={
					id:1,
					name:"andy"
				}
				//$.extend(taget,obj)
				$.extend(targetObj,obj);
				console.log(targetObj);//會覆寫targetObj裡面原來的值*/
				
				/*var targetObj={
					id:0
				};
				var obj={
					id:1,
					name:"andy",
					msg:{
						age:18
					}
				}
				//$.extend(taget,obj)
				//淺拷貝把原來對象裡面的複雜資料類型位址拷貝給目标對象
				$.extend(targetObj,obj);
				targetObj.msg.age=20;
				console.log(targetObj);
				console.log(obj);*/
				
				var targetObj={
					id:0,
					msg:{
						sex:"男"
					}
				};
				var obj={
					id:1,
					name:"andy",
					msg:{
						age:18
					}
				}
				//$.extend(taget,obj)
				//深拷貝把裡面的資料完全複制一份給目标對象,如果裡面有不沖突的屬性,會合并在一起
				$.extend(true,targetObj,obj);
				targetObj.msg.age=20;
				console.log(targetObj);
				console.log(obj);
			})
		</script>
	</head>
	<body>
	</body>
</html>
           
jQuery筆記jQuery筆記
jQuery筆記jQuery筆記

2、多庫共存

問題概述:

jquery使用$作為辨別符,随着jquery的流行,其他js庫也會用這作為辨別符,這樣一起使用就會引起沖突。

客觀需求:

需要一個解決方案,讓jquery和其他的js庫不存在沖突,可以同時存在,這就叫做多庫共存。

jquery解決方案:

  • 把裡面的$符号同意改為jquery。比如jquery(“div”)
  • jquery變量規定新的名稱: . n o C o n f l i c t ( ) v a r x x = .noConflict() var xx= .noConflict()varxx=.noConflict()
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="js/jquery.min.js" ></script>
		<script>
			$(function(){
				function $(ele){
					return document.querySelector(ele);
				}
				console.log($("div"));
				/*$.each();*/
				//解決沖突方案
				//1.如果$符号沖突,把$改成jquery
				jQuery.each()
				//2.讓jquery釋放對$控制權,可以自己決定
				var bl=jQuery.noConflict();
				console.log(bl("p"));
				bl("p").each(function(i,ele){
					console.log(i);
					console.log(ele)
				});
			})
			
		</script>
	</head>
	<body>
		<div></div>
		<p></p>
	</body>
</html>
           

3、jquery插件

jquery功能比較有限,想要更複雜的特效效果,可以借助于jquery插件完成。

注意:這些插件也是依賴于jquery來完成的,是以必須要先引入jquery檔案,是以也稱為jquery插件。

jquery插件常用的網站:

  • jquery插件庫:https://www.jq22.com jquery
  • jquery之家:http://www.htmleaf.com jquery

jquery插件使用步驟:

  • 引入相關檔案(jquery檔案和插件檔案)
  • 複制相關的html、css、js(調用插件)

jquery插件示範:

1.瀑布流(圖檔無序擺放):下載下傳jquery檔案,打開檔案的demo,檢視源代碼,然後再引入相關的js和css

2.圖檔懶加載(圖檔使用延遲加載可以提高網頁下載下傳速度。他也能幫助減輕伺服器負載)當我們頁面滑動到可視區區域,再顯示圖檔。

我們使用jquery插件庫EasyLazyload。注意,此時的js引入檔案和js調用必須寫道DOM元素(圖檔)最後面。

<body>
     <div>
		...
      </div>
    <script src="../js/jquery.min.js"></script>
	<script src="js/EasyLazyload.min.js"></script>
    <script>
	    lazyLoadInit({
	        coverColor:"white",
	        coverDiv:"<h1>test</h1>",
	        offsetBottom:0,
	        offsetTopm:0,
	        showTime:1100,
	        onLoadBackEnd:function(i,e){
	            console.log("onLoadBackEnd:"+i);
	        }
	        ,onLoadBackStart:function(i,e){
	            console.log("onLoadBackStart:"+i);
	        }
	    });
	</script>
</body>
           

3.全屏滾動(fullpage.js)

gitHub: https://github.com/alvarotrigo/fullPage.js

中文翻譯網站:http://www.dowebok.com/demo/2014/77

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<link rel="stylesheet" href="css/fullpage.min.css" />
		<style>
			.section1 { background: url(http://idowebok.u.qiniudn.com/77/1.jpg) 50%;}
			.section2 { background: url(http://idowebok.u.qiniudn.com/77/2.jpg) 50%;}
			.section3 { background: url(http://idowebok.u.qiniudn.com/77/3.jpg) 50%;}
			.section4 { background: url(http://idowebok.u.qiniudn.com/77/4.jpg) 50%;}
		</style>
		<script src="js/jquery.min.js" ></script>
		<script src="js/fullpage.min.js" ></script>
		<script>
			$(function(){
				$('#dowebok').fullpage({
					sectionsColor: ['#1bbc9b', '#4BBFC3', '#7BAABE', '#f90'],
					navigation: true,
					 continuousVertical: true,
					 navigationColor:"red"
					
				});
				setInterval(function(){
			        $.fn.fullpage.moveSectionDown();
			    }, 3000);
			});
		</script>
	</head>
	<body>
		<div id="dowebok">
	    <div class="section section1">
			<h3>第一屏</h3>
	    </div>
	    <div class="section section2">
	        <h3>第二屏</h3>
	    </div>
	    <div class="section section2">
	        <h3>第三屏</h3>
	    </div>
	    <div class="section section4">
	        <h3>第四屏</h3>
	    </div>
	</div>
	</body>
</html>
           

4、綜合案例 todolist案例

jQuery筆記jQuery筆記
html部分:
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<link rel="stylesheet" href="css/todolist.css">
		<script src="js/jquery.min.js"></script>
		<script src="js/todolist.js"></script>
	</head>
	<body>
		<header >
			<section class="w">
				<lable for="title">Todolist</lable>
				<input type="text" id="title" name="title" placeholder="添加ToDo" required="required">
			</section>
		</header>
		<section class="w">
			<h2>正在進行<span class="todocount" id="todoCount"></span></h2>
			<ol id="todolist" class="demo-box">
				
			</ol>
			<h2>已經完成<span class="todocount" id="doneCount"></span></h2>
			<ul class="donelist">
				
			</ul>
		</section>
		<footer >
			Copyright &copy; 2014 todolist.cn
		</footer>
	</body>
</html>

css部分:
*{
	padding:0;
	margin:0;
}
.w{
	width:700px;
	margin:0 auto;
	position: relative;
}
body{
	background-color: #ccc;
}
header{
	width:100%;
	height:40px;
	background-color: #000;
	color:#fff;
	font-size:26px;
	line-height: 40px;
}
#title{
	width:400px;
	height:30px;
	margin-left:150px;
	outline: none;
	position:absolute;
	top:50%;
	right:0;
	transform: translateY(-50%);
	border-radius: 5px;
	border:0;
	padding-left:5px;
}
h2{
	margin:15px 0;
}
.todocount{
	display: block;
	height:15px;
	background-color: #fff;
	padding:5px;
	float: right;
	font-size:12px;
	line-height: 15px;
	border-radius: 20px;
	margin-top:2px;
}
li{
	list-style: none;
	margin:10px 0;
	width:100%;
	height:40px;
	background-color: #fff;
	line-height: 40px;
	font-size:18px;
	padding: 0 5px;
	box-sizing: border-box;
	border-radius:5px;
}
li p{
	display: inline;
}
li a{
	text-decoration: none;
	display: inline-block;
	width:20px;
	height:20px;
	border:1px solid #4c4c4c;
	float: right;
	margin-top:10px;
	border-radius: 50%;
	position:relative;
}
li a::before{
	content: "";
	display: inline-block;
	width:15px;
	height:15px;
	background-color: #4c4c4c;
	border-radius: 50%;
	position:absolute;
	top:3px;
	left:2px;
}
.donelist li{
	background-color: rgba(255,255,255,0.3);
	color:#5e5e5e;
}
footer{
	margin-top:15px;
	text-align: center;
	color:#4c4c4c;
	
}

js部分:
$(function(){
	//按下回車 把完整的資料存儲到本地存儲裡面
	//存儲的資料格式:var todolist=[{title:"xxx",done:false}]
	load();
	$("#title").on("keydown",function(event){
		if(event.keyCode===13){
			if($(this).val()===""){
				alert("請輸入正确的内容")
			}else{
				//先讀取本地存儲原來的資料
				var local=getDate();
				console.log(local);
				//把local數組進行更新資料,把最近的資料追加給local數組
				local.push({title:$(this).val(),done:false});
				//把這個數組local存儲給本地存儲
				saveDate(local);
				//2.todolist本地存儲資料渲染加載到頁面
				load();
			}
			
		}
	})
	//toDoList 删除操作
	$("ol,ul").on("click","a",function(){
		//先擷取本地存儲
		var data=getDate();
		console.log(data)
		//修改資料
		var index=$(this).attr("id")
		console.log(index);
		data.splice(index,1);
		//儲存到本地存儲
		saveDate(data)
		//重新渲染頁面
		load();
	})
	//4.todolist正在進行和已經完成的選項操作
	$("ol,ul").on("click","input",function(){
		//先擷取本地存儲的資料
		var data=getDate();
		//修改資料
		var index=$(this).siblings("a").attr("id");
		console.log(index);
		data[index].done=$(this).prop("checked");
		//儲存本地存儲
		saveDate(data);
		//重新渲染頁面
		load();
	})
	//讀取本地存儲的資料
	function getDate(){
		var data=localStorage.getItem("todolist");
		if(data!==null){
			//本地存儲裡裡面的資料是字元串格式的,但是我們需要的是對象格式的
			return JSON.parse(data);
		}else{
			return [];
		}
	}
	//儲存本地存儲資料
	function saveDate(data){
		localStorage.setItem("todolist",JSON.stringify(data));
	}
	function load(){
		//周遊之前要清空ol裡面的元素内容
		$("ol,ul").empty();
		var todoCount=0;//正在進行的個數
		var doneCount=0;//已經完成的個數
		//讀取本地存儲的資料
		var data=getDate();
		//周遊這個資料
		$.each(data,function(i,n){
			if(n.done){
				$("ul").prepend("<li><input type='checkbox' checked='checked'> <p>"+n.title+"</p> <a href='javascript:;' id='"+i+"'></a></li>")
				doneCount++;
			}else{
				$("ol").prepend("<li><input type='checkbox'> <p>"+n.title+"</p> <a href='javascript:;' id='"+i+"'></a></li>");
				todoCount++;
			}
		})
		$("#todoCount").text(todoCount);
		$("#doneCount").text(doneCount);
	}
})
           

cn

css部分:

*{

padding:0;

margin:0;

}

.w{

width:700px;

margin:0 auto;

position: relative;

}

body{

background-color: #ccc;

}

header{

width:100%;

height:40px;

background-color: #000;

color:#fff;

font-size:26px;

line-height: 40px;

}

#title{

width:400px;

height:30px;

margin-left:150px;

outline: none;

position:absolute;

top:50%;

right:0;

transform: translateY(-50%);

border-radius: 5px;

border:0;

padding-left:5px;

}

h2{

margin:15px 0;

}

.todocount{

display: block;

height:15px;

background-color: #fff;

padding:5px;

float: right;

font-size:12px;

line-height: 15px;

border-radius: 20px;

margin-top:2px;

}

li{

list-style: none;

margin:10px 0;

width:100%;

height:40px;

background-color: #fff;

line-height: 40px;

font-size:18px;

padding: 0 5px;

box-sizing: border-box;

border-radius:5px;

}

li p{

display: inline;

}

li a{

text-decoration: none;

display: inline-block;

width:20px;

height:20px;

border:1px solid #4c4c4c;

float: right;

margin-top:10px;

border-radius: 50%;

position:relative;

}

li a::before{

content: “”;

display: inline-block;

width:15px;

height:15px;

background-color: #4c4c4c;

border-radius: 50%;

position:absolute;

top:3px;

left:2px;

}

.donelist li{

background-color: rgba(255,255,255,0.3);

color:#5e5e5e;

}

footer{

margin-top:15px;

text-align: center;

color:#4c4c4c;

}

js部分:

$(function(){

//按下回車 把完整的資料存儲到本地存儲裡面

//存儲的資料格式:var todolist=[{title:“xxx”,done:false}]

load();

KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲title").on("key…(this).val()===""){

alert(“請輸入正确的内容”)

}else{

//先讀取本地存儲原來的資料

var local=getDate();

console.log(local);

//把local數組進行更新資料,把最近的資料追加給local數組

local.push({title:$(this).val(),done:false});

//把這個數組local存儲給本地存儲

saveDate(local);

//2.todolist本地存儲資料渲染加載到頁面

load();

}

}
})
//toDoList 删除操作
$("ol,ul").on("click","a",function(){
	//先擷取本地存儲
	var data=getDate();
	console.log(data)
	//修改資料
	var index=$(this).attr("id")
	console.log(index);
	data.splice(index,1);
	//儲存到本地存儲
	saveDate(data)
	//重新渲染頁面
	load();
})
//4.todolist正在進行和已經完成的選項操作
$("ol,ul").on("click","input",function(){
	//先擷取本地存儲的資料
	var data=getDate();
	//修改資料
	var index=$(this).siblings("a").attr("id");
	console.log(index);
	data[index].done=$(this).prop("checked");
	//儲存本地存儲
	saveDate(data);
	//重新渲染頁面
	load();
})
//讀取本地存儲的資料
function getDate(){
	var data=localStorage.getItem("todolist");
	if(data!==null){
		//本地存儲裡裡面的資料是字元串格式的,但是我們需要的是對象格式的
		return JSON.parse(data);
	}else{
		return [];
	}
}
//儲存本地存儲資料
function saveDate(data){
	localStorage.setItem("todolist",JSON.stringify(data));
}
function load(){
	//周遊之前要清空ol裡面的元素内容
	$("ol,ul").empty();
	var todoCount=0;//正在進行的個數
	var doneCount=0;//已經完成的個數
	//讀取本地存儲的資料
	var data=getDate();
	//周遊這個資料
	$.each(data,function(i,n){
		if(n.done){
			$("ul").prepend("<li><input type='checkbox' checked='checked'> <p>"+n.title+"</p> <a href='javascript:;' id='"+i+"'></a></li>")
			doneCount++;
		}else{
			$("ol").prepend("<li><input type='checkbox'> <p>"+n.title+"</p> <a href='javascript:;' id='"+i+"'></a></li>");
			todoCount++;
		}
	})
	$("#todoCount").text(todoCount);
	$("#doneCount").text(doneCount);
}
           

})