js學習筆記——總

JavaScript 簡介

JavaScript誕生於1995年。起初它的主要目的是處理以前由服務器端負責的一些表單驗證。在那個絕大多數用戶都在使用調制解調器上網的時代,用戶填寫完一個表單點擊提交,需要等待幾十秒,完了服務器反饋給你說某個地方填錯了…在當時如果能在客戶端完成一些基本的驗證絕對是令人興奮的。當時走在技術革新最前沿的Netscape(網景)公司,決定着手開發一種客戶端語言,用來處理這種裝簡單的驗證。當時就職於Netscape公司的布蘭登·艾奇開始着手計劃將1995年2月發佈的LiveScript同時在瀏覽器和服務器中使用。爲了趕在發佈日期前完成LiveScript的開發,Netscape與Sun公司成立了一個開發聯盟。而此時,Netscape爲了搭上媒體熱炒Java的順風車,臨時把LiveScript改名爲JavaScript,所以從本質上來說JavaScript和Java沒什麼關係。

JavaScript 1.0獲得了巨大的成功,Netscape隨後在Netscape Navigator 3(網景瀏覽器)中發佈了JavaScript 1.1。之後作爲競爭對手的微軟在自家的IE3中加入了名爲JScript(名稱不同是爲了避免侵權)的JavaScript實現。而此時市面上意味着有3個不同的JavaScript版本,IE的JScript、網景的JavaScript和ScriptEase中的CEnvi。當時還沒有標準規定JavaScript的語法和特性。隨着版本不同暴露的問題日益加劇,JavaScript的規範化最終被提上日程。

1997年,以JavaScript1.1爲藍本的建議被提交給了歐洲計算機製造商協會(ECMA,European Computer Manufactures Association)該協會指定39號技術委員會負責將其進行標準化,TC39來此各大公司以及其他關注腳本語言發展的公司的程序員組成,經過數月的努力完成了ECMA-262——定義了一種名爲ECMAScript的新腳本語言的標準。第二年,ISO/IEC(國標標準化組織和國際電工委員會)也採用了ECMAScript作爲標準(即ISO/IEC-16262)

基本用法

js預解析

什麼是預解析

C語言要求函數必須先聲明後調用,js可以先調用而後聲明====js預解析 預解析是發生在當前作用域下的

JS的解析過程分爲兩個階段:預編譯期(預處理、預解析、預編譯)與執行期。

預編譯期JS會對本代碼塊(script)中的所有聲明的變量和函數進行處理,但需要注意的是此時處理函數的只是聲明式函數,而且變量也只是進行了聲明但未進行初始化以及賦值。 執行期就是在編譯後的基礎上開始從上到下執行腳本,遇到錯誤時中斷

預解析規則(優先級)

在js文件或者script裏面的代碼在正式開始執行之前,進行的一些解析工作。這個工作很簡單,就是在全局中尋找var關鍵字聲明的變量和通過function關鍵字聲明的函數。

同名的函數會替換掉 同名的 變量

方法的變量對象(VO)就會被以下屬性填充

  1. 參數,參數名就是VO中的名稱。值就是實參的值。如果沒有傳遞,則爲undefined
  2. 函數聲明,如果VO中中已經存在相同的屬性,則替換它的值
  3. 變量聲明:通過VO聲明的。在VO中的值爲undefined,如果VO中已經含有相同的屬性,則不會影響已經存在的屬性。

例子

console.log(a)
	var a=1
	console.log(a)
	function a(){
	    console.log(2)
	}
	console.log(a)
	var a=3
	console.log(a)
	function a(){
	    console.log(4)
	}
	console.log(a)
	a()


	// 預解析順序
	// var a = undefined
	// function a(){console.log(2)}  替換變量
	// function a(){console.log(4)}

	// 運行
	// console.log(a)   ======function a(){console.log(4)}
	// a = 1
	// console.log(a)   ==========1
	// console.log(a)       ======1
	// a = 3
	// console.log(a)     ===========3
	// console.log(a)     ===========3
	// a()              ==========報錯

console.log(a)
console.log(b)
fn1()
fn2()
var a=1
b=2
function fn1(){
    console.log(1)
}
var fn2=function(){
    console.log(2)
}
// 預解析順序
// var a = undefined
// var fn2 = undefined
// function fn1(){console.log(1)}

// 運行
// console.log(a)  ====== undefined
// console.log(b)  ======  報錯

function fn(a,b){
		console.log(a)
		console.log(b)

		var b=10
		function a(){}
	}
	fn(1,2)

// 查找函數參數
	// a:undefined
	// b:undefined
	// 查找函數聲明
	// function a(){} => a:function a(){}
	// 查找變量聲明
	// var b=10 => b:undefined

函數

函數作爲返回值

// 函數作爲返回值使用
	function write(){
		console.log('write')
		return function song() {
			/* body... */
			console.log('醜八怪')
		}
	}

	var returnSong = write();  //returnSong 是 function song(){...}
	returnSong();  //調用song();

函數作爲參數

// 函數作爲參數使用
	function say(gun) {
		/* body... */
		gun();     //---相當於hi(),調用了hi()這個方法
	}
	function hi() {
		/* body... */
		console.log('學的都忘記了,唉')
	}
	say(hi)   //把hi傳入say中

對象

向對象中添加數據

-obj.name = “張止水”;

向對象中修改數據

-obj[“name”] = “haha”

創建一個對象

var people = new Object();
	//添加屬性
	people.name = "張止水";
	people.age = 64;
	//添加方法
	people.eat = function () {
		/* body... */
		console.log('吃吃吃吃吃吃吃')
	}
	people.eat();

一次性創建多個對象

function createObject() {
		/* body... */
		var obj = new Object();
		obj.name = "紅紅";
		obj.age = 15;
		obj.run = function(){
			console.log('跑跑跑');
		}
		obj.sayHi = function(){
			console.log('Hi Hi Hi Hi');
		}
		return obj;
	}
	var dog1 = createObject();
	dog1.sayHi();

自定義構造函數

function People(){
		this.name = "朋小泰";
		this.age = 22;
		this.sex = "男";
		this.say = function (){
			console.log('....................')
		}
	}
	var people = new People()
	console.log('名字'+people.name+', 年齡'+people.age+',我想說');
	people.say();

字面量方式創建對象

var people = {
		name: "朋小泰",
		age: 22,
		sex: "男",
		sayhello: function () {
			/* body... */
			console.log('....................')
		}
	}
	console.log('名字'+people.name+', 年齡'+people.age+',我想說');
	people.sayhello();

	people["name"] = "haha"
	console.log('改動後的名字'+people.name);

數組

向數組中添加數據

count[0] = “哈哈”

count[1] = “huhu”

var perCount = parseInt(prompt("請輸入班級人數"));
	var perScores = [];
	for(var i=0; i < perCount; i++){
		perScores[perScores.length] = parseInt(prompt("請輸入第"+(i+1)+"個人的成績"))
	}
	console.log(perScores);

字符串

str.indexOf(searchvalue,fromindex)

searchvalue	必需。規定需檢索的字符串值。

fromindex	可選的整數參數。規定在字符串中開始檢索的位置。它的合法取值是 0 到 stringObject.length 					   - 1。如省略該參數,則將從字符串的首字符開始檢索

str.substr(start,length)

第二個參數可選。子串中的字符數。必須是數值。如果省略了該參數,那麼返回從 stringObject 的開始位置到結尾的字串。

截取字符串

// 截取字符串
	var str = "name=haha";
	var key = "="
	var index = str.indexOf("=");
	console.log(index);  //====4
	laststr = str.substr(index,key.length); 
	 //方法可在字符串中抽取從 start 下標開始的指定數目的字符。stringObject.substr(start,length)
	 //第二個參數可選。子串中的字符數。必須是數值。如果省略了該參數,那麼返回從 stringObject 的開始位置到結尾的字串。
	console.log(laststr)

查找字符串在哪個位置

var str="1231456178919871654";
	var index = 0;
	var key = "1";
	while ((index = str.indexOf(key, index)) != -1 ) {
		// statement
		console.log(index)
		index += key.length
	}
-----------輸出 
06-字符串.html:27 0
06-字符串.html:27 3
06-字符串.html:27 7
06-字符串.html:27 11
06-字符串.html:27 15

每個字符出現的次數

var str="XiangzheniyouduokunnanDUOXIAOHAI";
	//轉換大小寫
	str = str.toLocaleLowerCase();
	var obj = {};
	for(var i = 0; i < str.length; i++){
		key = str[i];
		if(obj[key]){
			//判斷對象中有沒有這個字母,如果有,值加1
			obj[key]++;
		}else{

			obj[key] = 1;
		}
	}

	// 遍歷對象輸出
	for(var key in obj){
		console.log(key + ":" + obj[key])
	}
-----------輸出
06-字符串.html:52 x:2
06-字符串.html:52 i:4
06-字符串.html:52 a:4
06-字符串.html:52 n:5
06-字符串.html:52 g:1
06-字符串.html:52 z:1
06-字符串.html:52 h:2
06-字符串.html:52 e:1
06-字符串.html:52 y:1
06-字符串.html:52 o:4
06-字符串.html:52 u:4
06-字符串.html:52 d:2
06-字符串.html:52 k:1

json

遍歷json格式

<body>
		<script>
			var json={
				"name":"小明",
				"age":"20",
				"color":"黑色"
			};
			for(var key in json){
				console.log(key+json[key]);//當對象中有屬性名字可以用  對象.屬性
			}
		</script>
	</body>

文檔對象模型 DOM

DOM的全稱是Document Object Model文檔對象模型

獲取對象

根據ID獲取

語法: documen.getElementById(‘id名’)

根據標籤名獲取

語法:document.getElementsByTagName(‘標籤名’)

例子:

<input type="button" value="點擊1" id="btn5">
<input type="button" value="點擊2" id="btn6">
<input type="button" value="點擊3" id="btn7">
var objinput = document.getElementsByTagName('input');
		for(var i = 0; i < objinput.length; i++){
			objinput[i].onclick = function () {
				alert("第"+ i + "個input");
			}
		}

根據類名獲取

語法:document.getElementsByClassName(“類名”)

返回文檔中所有指定類名的元素集合

<span class="green">摩天大樓 太稀有 人人高貴富有</span>
<p>表情溫柔 怕獻醜 沒人吐出骨頭</p>
<p>你們誰位居榜首</p>
<span  class="green">摩天大樓 雲裏走 謝絕衣衫簡陋</span>
<p>粉飾骷髏 氣質有 人們爭先恐後</p>
<span  class="green">她離開你心愛的蟻樓</span>
<input type="button" value="改變樣式" id="btn1"> 
document.getElementById('btn1').onclick = function () {
        var styles = document.getElementsByClassName("green");
        console.log(styles)
    //    遍歷每一個styles
        for(var i = 0; i < styles.length; i++){
            styles[i].style.color = "#009688";
            styles[i].style.backgroundColor = "#fff";
        }
    }

綁定事件和解綁事件

<input type="button" value="點擊事件1" id="btn"/>
<input type="button" value="解綁事件1" id="btn2" /><br />
<script>
  //第一種綁定事件
    var btn = document.getElementById('btn');
    var btn2 = document.getElementById('btn2');

    btn.onclick = function () {
        alert("點擊事件1")
    }
    btn2.onclick = function () {
        btn.setAttribute("disabled","disabled");
        btn.setAttribute("class","not");
    }
</script>
  1. addEventListener——兼容:firefox、chrome、IE、safari、opera;不兼容IE7、IE8


3.attachEvent——兼容:IE7、IE8;不兼容firefox、chrome、IE9、IE10、IE11、safari、opera

<input type="button" value="點擊事件3" id="btn5"/>
<input type="button" value="解綁事件3" id="btn6" /><br />
<script>
	document.getElementById('btn5').attachEvent('onclick',f2);
    document.getElementById('btn6').detachEvent('onclick',f2);
</script>

4.兼容代碼

<input type="button" value="點擊事件1" id="btn"/>
<input type="button" value="解綁事件1" id="btn2" /><br />
<script>
    //綁定事件的兼容代碼
    function addEventListener(element, type, fn) {
        if(element.addEventListener){
            element.addEventListener(type, fn, false);
        }else if(element.attachEvent){
            element.attachEvent(type, fn);
        }else{
            element["on" + type] = fn;
        }
    }

    //解綁事件兼容代碼
    function removeEventListener(element, type, fName) {
        if(element.removeEventListener) {
            element.removeEventListener(type, fName, false);
        } else if(element.detachEvent) {
            element.detachEvent(type, fName);
        } else {
            element["on" + type] = null;
        }
    }
    function f1(){
        console.log("哈哈2");
    }
    function f2(){
        console.log("哈哈哈3");
    }
    addEventListener(document.getElementById("btn"),"click",f1);
    addEventListener(document.getElementById("btn"),"click",f2);

    document.getElementById("btn2").onclick=function(){
   		removeEventListener(document.getElementById("btn"),"click",f1);
    }
</script>

事件方法

點擊事件

語法:對象.onclick = function(){}

例子:

<input type="button" name="" value="顯示圖片" id="btn2">
<input type="button" name="" value="隱藏圖片" id="btn3">
<img src="" alt="" id="img1">
document.getElementById('btn2').onclick = function () {
			var obj = document.getElementById('img1');
			obj.src = "../../static/img/14zhong.png";
			obj.width = "300";
			obj.height = "300"
			obj.style.display = "block";
		}
document.getElementById('btn3').onclick = function () {
			var obj = document.getElementById('img1');
			obj.style.display = "none";
		}

鼠標進入進出,移動事件

語法:對象.onmouseover (進入) 對象.onmouseout(移出) 對象.onmousemove(移動)

例子:(案例----淘寶圖片放大鏡)

<body>
		<ul>
			<li>蘇蘇</li>
			<li>哈哈哈</li>
			<li>黑惡虎</li>
			<li>阿西吧</li>
			<li>不是的</li>
		</ul>
	</body>
	<script>
		var list = document.getElementsByTagName("li");
		for (var i=0;i<list.length;i++) {
			//鼠標放上
			list[i].onmouseover = function(){
				this.style.backgroundColor="yellow";
			}
			
			//鼠標移除後
			list[i].onmouseout = function (){
				this.style.backgroundColor="";
				
			}
		}
	</script>

獲取焦點失去焦點事件

語法:對象.onblur(失去焦點) 對象.onfocus(獲取焦點)

例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    input {
        background:none;
        outline:none;
        border:0px;   /*去掉input默認樣式*/

        width: 150px;
        height: 50px;
        border-radius: 10px;
        box-shadow: 0 1px 1px #009688;
        /*box-shadow: h-shadow v-shadow blur spread color inset;
         h-shadow	必需的。水平陰影的位置。允許負值
         v-shadow	必需的。垂直陰影的位置。允許負值
         blur	可選。模糊距離
         spread	可選。陰影的大小
         color	可選。陰影的顏色。在CSS顏色值尋找顏色值的完整列表
         inset	可選。從外層的陰影(開始時)改變陰影內側陰影
         */
        padding-left: 10px;
    }
</style>
<body>
<input type="text" id="input1" value="請輸入內容">
</body>
<script>
    // 獲取焦點事件
    document.getElementById('input1').onfocus = function () {
        // alert("onfocus");
        if(this.value=="請輸入內容"){
            this.value="";
            this.style.color="#000";
        }
    }
    //失去焦點事件
    document.getElementById('input1').onblur = function () {
        // alert("onblur")
        if(this.value.length==0){
            this.value="請輸入內容";
            this.style.color="darkgray";
        }
    }
</script>
</html>

方法

innerText,textContent和innerHTML

用法:獲取文本,設置文本

1.innerText  谷歌,火狐,IE8都支持。textContent    谷歌,火狐支持,IE8不支持

2.innerText,textContent 獲取文本,設置文本,不解析html。innerHtml 可以解析html標籤

element.innerText = text;
element.textContent = text;
element.innerHTML = text;

var text = element.innerText;
var text = element.textContent;
var text = element.innerHTML;

元素和節點

基礎

node : 頁面中所有的內容,包括標籤,屬性,文本(文字,換行,空格,文本)

element:頁面中的所有標籤

元素是元素節點,是節點中的一種,但元素節點中可以包含很多的節點

節點的相關屬性:
    1.nodeType:節點類型      1——標籤   2——屬性   3——文本
    2.nodeName:節點的名字    標籤節點——大寫的標籤名字   屬性節點——小寫的屬性名字   文本節點——#text
    3.nodeValue:節點的值     標籤節點——null     屬性節點——屬性值   文本節點——文本內容
獲取相應的節點
    var uuobjs = document.getElementById('uu');

常用方法

1.父級節點——對象.parentNode

2.父級元素——對象.parentElement

3.子級節點——對象.childNodes

4.子級元素——對象.children

///下面的 IE8 子節點輸出的是子元素 ,子節點不支持--------------------------

5.第一個子節點——對象.firstChild

6.第一個子元素——對象.firstElementChild

7.最後一個子節點——對象.lastChild

8.最後一個子元素——對象.lastElementChild

9.某個元素前一個兄弟節點——對象.previousSibling

10.某個元素前一個兄弟元素——對象.previousElementSibling

11.某個元素最後一個兄弟節點——對象.nextSibling

12.某個元素最後一個兄弟元素——對象.nextElementSibling

<div id="dv">
    <span>span標籤</span>
    <ul id="uu">
        <li>美術</li>
        <li>數學</li>
        <li id="three">語文</li>
        <li>英語</li>
        <li>化學</li>
        <li>物理</li>
        <li>生物</li>
    </ul>
</div>
<script>
    var uuobjs=document.getElementById("uu");

    console.log("父級節點——")
    console.log(uuobjs.parentNode);
    console.log("父級元素——")
    console.log(uuobjs.parentElement);
    console.log("子級節點——")
    console.log(uuobjs.childNodes)
    console.log("子級元素——")
    console.log(uuobjs.children)
    ///下面的 IE8 子節點輸出的是子元素 ,子節點不支持--------------------------
    console.log("第一個子節點——") //====ie8 中是第一個子元素
    console.log(uuobjs.firstChild); //——#text  ----文本
    console.log("第一個子元素——") //ie8 underfind
    console.log(uuobjs.firstElementChild);  //<li>美術</li>
    console.log("最後一個子節點——") //======ie8 中是最後一個子元素
    console.log(uuobjs.lastChild)   //#text
    console.log("最後一個子元素——")
    console.log(uuobjs.lastElementChild);//<li>生物</li>


    var three = document.getElementById('three');
    console.log("某個元素前一個兄弟節點——");
    console.log(three.previousSibling);     //#text
    console.log("某個元素前一個兄弟元素——")
    console.log(three.previousElementSibling); //<li>生物</li>
    console.log("某個元素最後一個兄弟節點——");
    console.log(three.nextSibling);     //#text
    console.log("某個元素最後一個兄弟元素——");
    console.log(three.nextElementSibling);  //<li>英語</li>

</script>



<div id="dv">
			<p>這是一個單純的p標籤</p>
			<span>我是span 標籤</span>
			<ul>
				<li>理理理理理理</li>
			</ul>
		</div>
<script>
//			節點相關屬性:
//			nodeType:節點類型       1-----標籤   2-----屬性    3-----文本
//			nodeName:節點的名字   標籤節點----大寫的標籤名字    屬性節點----小寫的屬性名字   文本節點-----#text
//			nodeValue:節點的值    標籤節點-----null    屬性節點-----屬性值  文本節點----文本內容
			
//			獲取裏面的所有子節點
			var dvObjs=document.getElementById("dv");
			//子節點(包括標籤, 屬性, 文本( 文字, 換行, 空格, 文本))
			console.log(dvObjs.childNodes);
			//7個NodeList(7) [text, p, text, span, text, ul, text]
			
			//子元素(標籤)
			console.log(dvObjs.children);
			//HTMLCollection(3) [p, span, ul]
			
			for (var i=0;i<dvObjs.childNodes.length;i++) {
				var nodes=dvObjs.childNodes[i];
				console.log(nodes.nodeType+"--------"+nodes.nodeName+"------"+nodes.nodeValue);
			}
			
		</script>

創建元素

1.document.write

2.對象.innerHTML = “”

3.document.createElement

例一

<input type="button" value="點擊" id="btn" /><br />
<input type="button" value="點擊二" id="btn2"/><br />
<input type="button" value="點擊三" id="btn3" />
<div id="dv"></div>
<div id="dv2" class="dv2"></div>
<script>
    document.getElementById("btn").onclick = function() {
        document.write(`
            <p>hahahhah</p>
        `);
    }
    document.getElementById('btn2').onclick = function () {
        document.getElementById('dv').innerHTML = `<p>窗前明月光</p><p>疑是地上霜</p>`
    }
    document.getElementById('btn3').onclick = function () {
    //    創建元素的對象
        var pobj = document.createElement('p');
    //    在標籤中添加內容'
        pobj.innerText = 'hahahahahah';
        document.getElementById('dv2').appendChild(pobj);

    }

</script>

例二

<input type="button" value="添加元素" id="btn"/><br />
<div id="dv" style="height: 300px; width: 300px; border: 3px dashed #6495ED;">
</div>
<script>
document.getElementById('btn').onclick = function () {
    var song = ["初學者", "動物世界", "駱駝", "方圓幾裏", "像風一樣"];
    var str = `<ul style="list-style: none;cursor: pointer;">`;

    //循環,爲每一個添加<li>
    for(var i = 0; i < song.length; i++){
        str += "<li>" + song[i] + "</li>";
    }
    str += "<ul/>"

    document.getElementById('dv').innerHTML = str;

    var list = document.getElementsByTagName('li');

    for(var j = 0; j < list.length; j++){
        list[j].onmouseover = function () {
            this.style.color = "#009688";
        }
        list[j].onmouseout = function () {
            this.style.color = "";
        }
    }
}
</script>

案例

tab選項卡

總結:

1.css中 .head span.show

2.js在點擊選項卡頭部的時候需要添加一個index,用於判斷內容的顯隱

  1. js 的 setAttribute 方法添加指定的屬性,併爲其賦指定的值.如果這個指定的屬性已存在,則僅設置/更改值。 getAttribute返回指定屬性名的屬性值。 removeAttribute法刪除指定的屬性。
    jquery的刪除屬性 removeAttr 。 attr()方法也用於設置/改變屬性值
  2. js 的設置類名
    添加:document.getElementById(“id”).classList.add(“類名”);
    刪除:document.getElementById(“id”).classList.remove(“類名”);
    var classVal=document.getElementById(“id”).getAttribute(“class”);
    添加:document.getElementById(“id”).setAttribute(“class”,classVal.concat(" 類名"));
    刪除:document.getElementById(“id”).getAttribute(“class”).replace(“類名”," “);
    document.getElementById(“id”).className+=” 類名";
  3. jquery 設置類名 addClass()方法向被選元素添加一個或多個類。 removeClass()方法從被選元素移除一個或多個類。

css:

 .box {
        width: 50%;
        margin: 0 auto;
    }
    .head {
        width: 100%;
        height: 50px;
    }
    .head span {
        display: block;
        float: left;
        width: 24%;
        margin-left: 1%;
        line-height: 50px;
        text-align: center;
        background-color: pink;
        color: #fff;
        cursor: pointer;
    }
    .head span.show {
        background-color: #009688;
    }
    .body {

    }
    .ull {
        list-style: none;
        margin: 0px;
        padding-left: 1%;
        width: 99%;

    }
    .ull li {
        display: none;
        width: 100%;
        height: 200px;
        background-color: #009688;
        text-indent: 20px;   /** 設置字體開頭縮進距離**/
        letter-spacing: 2px;  /**字符間距*/
    }
    .ull li.show {
        display: block;

    }

html:

<!--tab選項卡-->
<div class="box" id="box">
    <div class="head">
        <span class="show">體育</span>
        <span>娛樂</span>
        <span>新聞</span>
        <span>綜合</span>
    </div>
    <div class="body">
        <ul class="ull">
            <li class="show">我是體育</li>
            <li>我是娛樂</li>
            <li>我是新聞</li>
            <li>我是綜合</li>
        </ul>
    </div>
</div>

js:

 var box = document.getElementById('box');
    var head = box.getElementsByTagName('div')[0];
    var body = box.getElementsByTagName('div')[1];
    var spans = head.getElementsByTagName('span');
    var lii = body.getElementsByTagName('li');
    for(var i = 0; i < spans.length; i++){
    //    爲每個span註冊點擊事件 ---點擊時加 show 不點擊時其他的都沒有 show這個class
    //    需要添加一個index
        spans[i].setAttribute("index",i);
        spans[i].onclick = function () {
            for(var j = 0; j < spans.length; j++){
                spans[j].removeAttribute("class")
            }
            this.className = "show";
        //    獲取index
            var index = this.getAttribute("index");
        //    遍歷li標籤,去除所有樣式
            for(var k = 0; k < lii.length; k++){
                lii[k].removeAttribute("class")
            }
            lii[index].className = "show";
        }
    //    爲對應的li添加  show ,其他的沒有

    }

定時器隨機抽中

總結:

css:

body {
        height: 800px;
        /*width: 800px;*/
    }

    ul {
        width: 80%;
        margin: 0 auto;
        height: 80%;
    }

    div {
        background-color: #009688;
        width: 33%;
        margin-left: 0.3%;
        margin-top: 0.3%;
        height: 33%;
        float: left;
        text-align: center;
        line-height: 220px;
    }

html:

<input type="button" id="start" value="開始">
<input type="button" id="stop" value="結束">
<ul>
    <div>李白</div>
    <div>孫尚香</div>
    <div>程咬金</div>
    <div>蘭陵王</div>
    <div>妲己</div>
    <div>上官婉兒</div>
    <div>鎧</div>
    <div>露娜</div>
    <div>大魚</div>
</ul>

js:

function randomNum(minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                break;
            default:
                return 0;
                break;
        }
    }

    var dv = document.getElementsByTagName('div');
    var timer;
    document.getElementById('start').onclick = function () {
        timer = setInterval(function () {
            var max = dv.length-1;
            var index = parseInt(randomNum(0,max));
            for (var k = 0; k < dv.length; k++) {
                dv[k].style.backgroundColor = "#009688"
            }
            dv[index].style.backgroundColor = "pink"
        }, 50);
    }
    document.getElementById('stop').onclick = function () {
        clearInterval(timer);
    }

innerText和textContent兼容代碼

html

<input type="button" value="改變文本" id="btn1"/>
<div id="dv">這是一個神奇的網站</div>

js

 //設置文本
    function setText(element,text) {
        if(typeof element.textContent === "undefined"){
            element.innerText = text;
        }else {
            element.textContent = text;
        }
    }
//    獲取文本
    function getText(element) {
        if(typeof element.textContent == "undefined"){
            return element.innerText;
        }else {
            return element.textContent;
        }
    }

    document.getElementById('btn1').onclick = function () {
        var element = document.getElementById('dv');
        var text = "改變了哈"
        setText(element,text);
        alert(getText(element))
    }

淘寶圖片放大鏡

css:

  img {
        width: 250px;
        height: 250px;
    }
    .imgbag {
        position: relative;
        width: 250px;
        height: 250px;
        float: left;
    }
    /*遮罩層*/
    .shadow {
        width: 75px;
        height: 75px;
        background-color: darkred;
        opacity: 0.3;
        position: absolute;
        display: none;
    }
    .big {
        width: 250px;
        height: 250px;
        float: left;
        background-color: #ffffff;
        opacity: 1;
        /*filter: opacity(1);*/
        overflow: hidden;   /*溢出隱藏、清除浮動、解決外邊距塌陷*/
        display: none;
    }
    .bigimg {
        height: 400px;
        width: 400px;
        background-repeat: no-repeat;
        background-size: cover;
        position: relative;
    }

html:

 <!--原始圖片區域-->
    <div class="imgbag" id="imgbox">
        <!--遮罩層---放大區域-->
        <div class="shadow" id="shadow"></div>
        <img src="../../static/img/cat.png">
    </div>
    <!--放大圖片區域-->
    <div class="big" id="big">
        <img src="../../static/img/cat.png" id="bigimg" class="bigimg">
    </div>

js:

  var imgbox = document.getElementById('imgbox');
    var shadow = document.getElementById('shadow');
    var big = document.getElementById('big');
    var bigimg = document.getElementById('bigimg');

    //鼠標移入事件,讓放大鏡和放大區顯示!
    imgbox.onmouseover = function () {
        shadow.style.display = "block";
        big.style.display = "block";
    }
    // //鼠標不斷移動時觸發,實時更新放大鏡得到的圖片
    imgbox.onmousemove = function(){
        //1 shadow  2,imgbox 3 imgbig 4 big
        floatMove(shadow, imgbox, event);
        showPic(shadow,imgbox,bigimg,big);
    }

    //鼠標移出後,放大鏡和放大區隱藏
    imgbox.onmouseout = function () {
        shadow.style.display = "none";
        big.style.display = "none";
    }
    //由於offset方法包括邊框,在使用的時候很容易出現問題,所以用style來實時獲取attr!
    function getStyle(obj, attr) {
        if (window.currentStyle) {
            return parseInt(obj.currentStyle[attr]);
        }
        else {
            return parseInt(getComputedStyle(obj,null)[attr]);
        }
    }
    //運動框架,控制放大鏡在原圖中的位置!
     function floatMove(element1,element2,event) {
        var e = event || window.event;
        var minleft = getStyle(element1,"width");    //得到原始圖片的寬,高
        var minHeight = getStyle(element1, "height")- minleft/2;;

        var maxleft = getStyle(element2,"width");    //得到放大圖片的寬,高
        var maxHeight = getStyle(element2, "height") - minHeight/2;

        if (e.clientX < minleft/2) {
            element1.style.left = "0px";//防止放大鏡超出左邊框
        }
        else if (e.clientX > maxleft) {
            element1.style.left = getStyle(element2, "width") - getStyle(element1, "width") + "px";//防止放大鏡超出右邊框
        }
        else {
            element1.style.left = event.clientX - minleft/2 + "px"; //放大鏡完全在圖片內時正常移動
        }
        if (e.clientY < minHeight/2) {
            element1.style.top = "0px"; //防止放大鏡超出上邊框
        }
        else if (e.clientY > maxHeight) {
            element1.style.top = getStyle(element2, "height") - getStyle(element1, "height") + "px"; //防止放大鏡超出下邊框
        }
        else {
            element1.style.top = event.clientY - minleft/2 + "px";
        }
    }
    //用來顯示放大鏡得到的圖片,利用座標計算!實時更新可視區域
   function showPic(element1,element2,element3,element4) {     
     //element1  遮罩層對象   element2  原始圖片區域
     //element3	 放大圖片	  element4  放大圖片區域
        var iCurLeft = getStyle(element1,"left");
        var iCurTop = getStyle(element1,"top");
        var a = getStyle(element2,"width") - getStyle(element1,"width");
        var b = getStyle(element3,"width") - getStyle(element4,"width");
        var moveWidth = -(iCurLeft/a)*b;
        element3.style.left = moveWidth + "px";
        var c = getStyle(element2,"height") - getStyle(element1,"height");
        var d = getStyle(element3,"height") - getStyle(element4,"height");
        var moveHigth = -(iCurTop/c)*d;
        element3.style.top = moveHigth + "px";
    }

搜索框下的提示

<style>
    input,p{
        margin: 0px;
        padding: 0px;
    }
    body {
        width: 100%;
    }
    .dv {
        margin: 0 auto;
        width: 100%;
    }
    .dv .text{
        width: 536px;
        height: 36px;
        line-height: 36px;
        padding-left: 10px;
        border: 0px;
        border: 1px solid #cccccc;
    }
    .dv .btn{
        cursor: pointer;
        width: 108px;
        height: 40px;
        line-height: 40px;
        margin-left: 0px;
        padding-left: 0px;
        border: 1px solid #38f;
        background-color: #38f;
        outline: none;    /*//消除默認點擊藍色邊框效果*/
        color: #fff;
    }

</style>
<body>
<div id="dv" class="dv">
    <input type="text" value="" id="text" maxlength="100" class="text">
    <input type="button" value="搜索" id="" class="btn"></input>
</div>
</body>
<script>
    var keywords = ["月餅不好吃", "月亮很圓", "CSS 是什麼", "CSS怎麼學習", "HTML 和HTML5 的區別",
        "js中怎麼遍歷數組", "唐宋的詩人有哪些欸", "李白王者峽谷第一美男", "李白是唐朝的詩人", "李白是怎麼死的"
    ];

//    監聽輸入框---鍵盤擡起
    document.getElementById('text').onkeyup = function () {
        //輸入前清除div
        if(document.getElementById('sousuo')){
            document.getElementById('dv').removeChild(document.getElementById('sousuo'));
        }
        //獲取文本框輸入內容
        var textobj = this.value;
        //遍歷數組
        var str = [];
        for(var i = 0; i < keywords.length; i++){
            //判斷輸入的是否匹配
            if(keywords[i].indexOf(textobj) == 0){
                str.push(keywords[i]);
            }
        }

        if(this.value.length == 0 || str.length == 0){
            //如果頁面有這個div刪除
            if(document.getElementById('sousuo')){
                document.getElementById('dv').removeChild(document.getElementById('sousuo'));
            }
            return ;
        }

        //創建div,把str追加到div中
        var sousuo = document.createElement("div");
        document.getElementById('dv').appendChild(sousuo);
        sousuo.id = "sousuo";
        sousuo.style.width = "546px";
        sousuo.style.border = "1px solid #ccc";
        //創建p標籤
        for(var j = 0; j < str.length; j++){
            var pobj = document.createElement('p');
            pobj.innerText = str[j];
            pobj.style.paddingLeft="10px";
            pobj.style.height = "30px"
            pobj.style.lineHeight = "30px"
            pobj.style.fontSize = "12px"

            sousuo.appendChild(pobj);

            pobj.onmouseover=mouseoverEvent;
            pobj.onmouseout=mouseoutEvent;

        }
        function mouseoverEvent(){
            this.style.backgroundColor="#eef0f3";
        }
        function mouseoutEvent(){
            this.style.backgroundColor="";
        }
   }
</script>

分割

瀏覽器對象模型 BOM

BOM的全稱是Browser object modelBOM由多個對象組成,其中代表瀏覽器窗口的window對象是BOM的頂層對象,其他對象都是該對象的子對象。

頂層對象:window

子對象:location、history、screen、navigator、document、event

window對象

alert 彈出框

用法:window.alert() 或者 alert()

confirm 對話框

用法:window.confirm();或 confirm();

功能:顯示一個帶有指定消息的和 確定及取消按鈕的對話框

返回值:用戶點擊確定,confirm() 返回true

          用戶點擊取消,confirm() 返回false

<script>
var value = confirm("confirm選擇框");
if(value){
	console.log(1);
}else{
	console.log(2);
}
</script>

prompt 對話框

語法:window.prompt( text[,defaultText] );或者 prompt( text[,defaultText] );

參數: text:要在對話框中顯示的純文本(不是HTML格式文本)

     defaultText:默認的輸入文本

返回值:如果用戶點擊提示框的取消按鈕,則返回null

	如果用戶點擊確定按鈕,則返回輸入的內容

open打開瀏覽器窗口

語法:window.open(pageURL,name,parameters)

功能:打開一個新的瀏覽器窗口或查找一個已名稱的窗口

參數:pageURL:路徑

    name:窗口名字

    parameters:窗口參數(逗號分隔)
  • width 窗口寬度、

  • height 窗口高度、

  • left 窗口X軸座標、top 窗口Y軸座標

  • toolbar 是否顯示瀏覽器工具欄(yes/no)、

  • menubar 是否顯示菜單欄(yes/no)、

  • scrollbars 是否顯示滾動條(yes/no)、

  • location 是否顯示地址字段

  • status 是否添加狀態欄

    function openMailBox(){
    window.open(‘new.html’,‘消息通知’,‘width=800,height=600,left=30%,top=30%,toolbar=no,menubar=no,location=no,status=no’);
    }

close 關閉瀏覽器窗口

語法:window.close()

功能:關閉瀏覽器窗口

setTimeout 計時器

語法:setTimeout(code,millisec)

功能:在指定的毫秒數後調用函數或計算表達式

參數:code:要調用的函數名或者要執行的js代碼

    millisec:在執行代碼前等待的毫秒數

備註:setTimeout只執行一次code, 多次調用需使用setInterval, 也可以讓code自己調用自己

<script>
	//匿名函數
	setTimeout(function(){console.log(1)},2000);
 
	//聲明函數
	setTimeout(fn,3000);    //不要寫成setTimeout(fn(),3000); 函數名() 這樣會直接調用函數
	function fn(){
		console.log(2);
	}
</script>

clearTimeout 消除計時器

語法:clearTimeout(id_of_settimeout);

功能:取消由setTimeout()方法設置的超時調用

參數:setTimeout 返回的id值

<script>
	//匿名函數
	var ID = setTimeout(function(){console.log(1)},2000);
	clearTimeout(ID);    //這樣 超時調用將不會被執行
</script>

setInterval 計時器

語法:setInterval(code,millisec)

功能:每隔指定的時間執行一次代碼

參數:code:要調用的函數名或者要執行的js代碼

    millisec:在執行代碼前等待的毫秒數

<script>
	//匿名函數
	var ID = setInterval(function(){console.log(1)},2000);
 
	//聲明函數
	setInterval(fn,3000);
	function fn(){
		console.log(2);
	}
</script>

clearInterval 清楚計時器

語法:clearInterval(id_of_setinterval)

<script>
	//匿名函數
	var ID = setInterval(function(){console.log(1)},2000);
	clearInterval(ID);
</script>

location對象

location對象提供了與當前窗口中加載的文檔有關的信息,還提供了功能,它既是window對象的屬性,也是document對象的屬性

location.href

獲取url

語法:location.href

功能:返回當前頁面完整的url

備註:location.href 和 window.location.href 等價(window可以省略)

設置url

語法:location.href = url ;

功能:跳轉到 指定的url中

location.hash 錨點鏈接

獲取錨點

語法:location.hash

功能:返回url中hash(#以及後面的字符),如果不含,返回空字符串

<script>
//當前url爲例:http://localhost/Web/JS/dom.html#fuck
	console.log(location.hash);    //輸出#fuck
</script>

設置錨點

語法:location.hash = “#aaa”

功能:爲url添加指定的錨點,實現頁面的錨點位置跳轉

<a href="#bottom">到底部</a>
<div id="div1" class="red" data-name="poorpenguin" style="height: 1000px;">
	<p>測試1</p>
</div>
<div>
	<p>測試2</p>
</div>
<a id="bottom">這是底部</a><!-- 這是錨點 -->
 
<script>
	//當前url爲例:http://localhost/Web/JS/dom.html
	location.hash = '#bottom';    //打開當前頁面會默認轉到location.hash的指定的錨點位置
</script>

location對象

<script>
	//當前url爲例:http://localhost/Web/JS/dom.html?id=1&name=poorpenguin
	console.log(location.host);	//返回服務器名稱和端口號(如果有)	localhost
	console.log(location.hostname);	//返回不帶端口號的服務器名稱	localhost
	console.log(location.pathname);	//返回url中的目錄和文件名	        /Web/JS/dom.html
 
	console.log(location.port);	//返回url中指定的端口號,如果沒有,返回空字符串
	console.log(location.protocol);	//返回頁面使用的協議	        http:
	console.log(location.search);	//返回url的查詢字符串,這個字符串以問號開頭	?id=1&name=poorpenguin
</script>

location.replace 重新定向url

語法:location.replace(url)

功能:重新定向url

備註:使用location.replace不會在歷史紀錄中生成新紀錄(沒有後退按鈕)

<script>
	location.replace('//wwww.baidu.com');    //頁面對跳轉到www.baidu.com
</script>

location.reload重新加載

語法:location.reload()

功能:重新加載當前界面

備註:location.reload()有可能從瀏覽器緩存中加載

  location.reload(true)	強制從服務器中重新加載

histroy對象

histroy對象保存了用戶在瀏覽器中訪問頁面的歷史紀錄

histroy.back()

語法:histroy.back()

功能:回到歷史紀錄的上一步

備註:相當於使用 histroy.go(-1)

histroy.forward()

語法:histroy.forward()

功能:回到歷史記錄的下一步

備註:相當於使用histroy.go(1)

histroy.go(-n)

語法:histroy.go(-n)

功能:回到歷史記錄的上n步

histroy.go(n)

語法:histroy.go(n)

功能:回到歷史記錄的下n步

screen對象

screen對象包含有關客戶端顯示屏幕的信息

可用屏幕寬/高度

<script>
	console.log("屏幕寬度"+screen.availWidth);    //是定死的屏幕寬度
	console.log("屏幕高度"+screen.availHeight);    //是定死的屏幕高度
</script>

窗口文檔顯示寬/高度

	console.log("pageWidth:"+window.innerWidth);    //就是瀏覽器顯示頁面的窗口寬度
	console.log("pageHeight:"+window.innerHeight);    //就是瀏覽器顯示頁面的窗口高度

navigator

提供了用戶的瀏覽器、操作系統等信息,可通過當前對象得知用戶所用瀏覽器類型、版本等

navigator.userAgent 瀏覽器類型

語法:用來識別瀏覽器名稱、版本、引擎、以及操作系統等信息

<meta charset="UTF-8">
<title>userAgent</title>
</head>
<body>
<input type="button" value="點擊獲取瀏覽器信息" id="browser">
<script type="text/javascript">
document.getElementById("browser").onclick=function(){
    var browserInfo = navigator.userAgent;
    var browerName = judgeTypeOfBrowser(browserInfo);
    alert('您使用的瀏覽器是 '+browerName+' 瀏覽器');
}
/*判讀瀏覽器類型*/
function judgeTypeOfBrowser(browerInfo){
    var browerInfoLowerCase = browerInfo.toLowerCase(); //轉小寫
    //瀏覽器種類
    var browser = [
      {type:'msie',name:'IE瀏覽器'},
      {type:'firefox',name:'火狐瀏覽器'},
      {type:'chrome',name:'谷歌瀏覽器'},
      {type:'safari',name:'Safari瀏覽器'}
    ];
    for(var i=0,len=browser.length; i<len; ++i){
      if(browerInfoLowerCase.indexOf(browser[i].type)>0)return browser[i].name; //返回
    }
    return '未知';
}
</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章