前端篇—javascript

JavaScript

介紹

    JavaScript是一種直譯式腳本 語言,是一種動態類型、弱類型、基於原型的語言,內置支持類型。它的解釋器被稱爲JavaScript引擎,爲瀏覽器的一部分,廣泛用於客戶端的腳本語言,最早是在HTML(標準通用標記語言下的一個應用)網頁上使用,用來給HTML網頁增加動態功能。
    在1995年時,由Netscape公司的Brendan Eich,在網景導航者瀏覽器上首次設計實現而成。因爲Netscape與Sun合作,Netscape管理層希望它外觀看起來像Java,因此取名爲JavaScript。但實際上它的語法風格與Self及Scheme較爲接近。

ECMA

    ECMAscript是基於Netscape javaScript的一種標準腳本語言。它也是一種基於對象的語言,通過DOM可以操作網頁上的任何對象。可以增加、刪除、移動或者改變對象。使得網頁的交互性大大提高。

基礎

  1. 變量
//初始化變量
var a=1, b=2;
var s='wolf';
var f=3.3;
  1. 註釋
/*1.
註釋
*/

// 2. 註釋
  1. 常量
  2. 標識符
  3. 數據類型
  4. Number:數字
    Null:空對象,佔一個對象空間。
    String:字符串
    Undefined:var a;聲明一個變量不賦值
    Boolean:布爾類型
    object:
    array;

運算符、數據轉換

  1. 數據類型轉換
    Number+ String= String:數字被轉換成字符串與字符串拼接
    Number+ Boolean= Number+ 1/0:True == 1 /False == 0.
    String+ Boolean= String;

    parseInt(3.14); --> 3 ;將數字類型轉換成整型;取整數部分
    parseInt(“3.54m”); --> 3;將字符串前面的數字轉換成整型;
    parseInt(“n3.14n”); --> 將字符串轉換成數字失敗時就是NaN,屬於Number;
    NaN數據在表達式中,結果就一定時False,除了 != ;

  2. 查看數據類型

var n = null;
typeof(n);		// 只能判斷基礎類型
 	//--> object;	
  1. 運算符
var b = a++; 	//a += 1
// 先賦值,後運算,--> b==1,a==2;
var b = ++a;
// 先運算,後賦值, --> b==2, a==2;
c = b + '314hello';  //NaN; 在運算中不能將含有非數字的字符串轉換成數字;
  1. 邏輯運算符
    && 與
    || 或
    & 按位與
    | 按位或
    >> 左移
    << 右移
    ~ not

  2. 賦值運算符

    全等於、全不等於(不進行數據轉換,直接進行比較):

	2 == '2'; 		-->		true;
	2 === '2'; 		-->		false;
	4 != '4';		-->		false;
	4 !== '4'; 		-->		true;
  1. 等性運算符
null == undefined		-->		true
'NaN' == NaN			-->		false
4 == NaN				-->		false
NaN == NaN				-->		false
NaN != NaN				-->		true
false == 0				-->		true
true == 1				-->		true
true == 2				-->		false
undefined == 0			-->		false
null == 0				-->		false
5 == '5'				-->		true	

  1. 關係運算符
25 < 3;			-->		false
25 < '3';		-->		true

//兩邊數據類型分別爲字符串和數字時,轉換成數字比較
  1. boolean運算符*
  2. void()
    void運算符對任何值返回undefined 。用於避免輸出不應該輸出的值。

控制語句

if-else語句

<script>
	if (bool){
		alert()
	} else if(bool){
		alert()
	}else{
		alert()
	}
</script>

switch語句

var x=1;
switch(x){
    case 1:alert(1);brek;
    case 2:alert(2);brek;
    case 3:alert(3);brek;
    case 4:alert(4);brek;
    default:alert(5)
}
//直接將x與case後面的數據比較,相同時執行後面的代碼,都不相同時執行default,每個case後面加break;
//不用判斷條件語句,相比if-else語句效率更高

for語句

// 格式一
var a = [1, 'i', false]
for (var i in a){
	console.log(i);
	console.log(a[i]);
}
// --->	結果i爲0,1,2
//	通過a[i]索引才能得到a中的值
// 格式二
for (var i=0;i<10;i++){
    console.log(i);
}
// js中for循環計算1~100的和
var sum=0;
for (var i=1;i<101;++i){
    sum+=i;
}
alert(sum);	// 在瀏覽器中顯示彈窗;

在這裏插入圖片描述

for (var i=1;i<7;i++){
    document.write('<h'+i+'>h'+i+'</h'+i+'>')
}

在這裏插入圖片描述

obj = {'1':'111'};	//一個對象,取值類似python中的字典
document.write(obj,'=====',typeof(obj), '=====')

for (var i in obj){
    document.write(i, '======', obj[i])
}

[object Object]=object=1======111

while語句

// while寫1~100的和
var sum=0,i=0;
while(i<101){
    sum += i;
    i++;
}
document.write(sum)

try語句

try{
	// 代碼塊
}catch (e){
	// try代碼塊報錯時,執行catch代碼塊
	// e是一個局部變量,指向報錯對象
}finally{
	// 在此try代碼塊中,一定會執行的代碼快	
}

對象

  • 核心(ECMAScript)
  • 文檔對象模型(DOM:Document object model (整合js,css,html)
  • 瀏覽器對象模型(BOM):Broswer object model(整合js和瀏覽器)
  • 11種內置對象:array、string、date、math、boolean、number、function、global、error、regexp、object
  1. function
// 方法1
function func1() {
    alert(3);
    return 0
}
var ret=func1();
alert(ret)
// 方法2,Function中F需要大寫
var foo1=new Function('a','b','alert(a+b)');
foo1(1, 2)

屬性和方法:

alert(foo1.length);
// 參數的個數
function foo(){
	var a=3;
}
foo();
alert(a);
// -->  a is not defined;

在這裏插入圖片描述

function foo(){
	a=3;	// 直接寫a=3; a爲全局變量
	var b=5;
	b=6;	// 也可能是局部變量的修改,所以儘量使用局部變量;
}
func();
alert(a)

在這裏插入圖片描述

var s='wolf';
s instanceof String		// --> true
var n=2;
n instanceof String 	// --> false

String字符串對象

document.write(s.length)	// 字符串長度

document.write(s.bold(),'<br>');    // 返回加粗字符串 <b>s<b>
document.write(s.sup(),'<br>');     // 返回上標格式字符串 <sup>s</sup>
document.write(s.italics(),'<br>'); // 返回不同字體格式

s.toLowerCase();		// 轉換爲小寫
s.toUpperCase();		// 轉換爲大寫

s.charAt(index);		// 返回index索引下的字符
s.charCodeAt(index);	// 返回index索引下字符的unicode編碼

s.indexOf('l');		// 取str在s中的索引
s.lastIndexOf("l");	// 從右往左倒着找索引
s.match('ol');	// 返回包含所有匹配結果的數組,沒有匹配返回null,參數爲正則表達式或者字符串
s.search('ol');	// 返回匹配字符串的首字符位置索引

s.substring(start, end)		// 截取字符串start-end的部分
s.substr(start, length)		// 截取字符串start-(start+length)的部分
s.slice(start, end)			//// 截取字符串start-end的部分,end可以爲負數:-1爲最後一個數.-2爲倒數第二個數

s.replace(old, new)			// 替換字符串

s.split(",")				// 將字符串按,分割

s.concat(s2)				// 返回s+s2

Array數組對象

// 創建方法1
var a=[1,2,3];
// 創建方法2
var a1=new Array[1,2,3,4,5]
// 創建方法3
var a2=new Array(5);	// 一個數字時代表數組長度,佔5個位置,但長度是可變的,都是defined類型
// 初始化數組對象
a2[0]=1;
a2[1]='a2';
a2[2]=true;
a2[3]=3;
a2[4]='wolf';
// 直接創建二維數組
a2[3][0]=1;
a2[3][1]=2;
a2[3][3]=3;
a.length;	//對象長度

var s=a.join('-')		// 以-連接數組
// python中的join是字符串方法,s='-'.join(['1','2','3'])
js中的join是數組方法:s=(['1','2','3']).join('-')
a.toString();		// 轉換成字符串

a.slice(2, 4) 	// 切片

a. splice(start, deleteCount, value, ...)
// 從start位置刪除deletecount個參數,再添加value(可省略)

a.push(value, ...)  // 壓棧,在數組最後添加value
a.pop()             // 彈棧,刪除最後一個元素
a.unshift(value,...)// 在數組最開始位置添加value
a.shift()			// 刪除第一個元素

a.reverse()		// 反向
a.sort()		// 按ascii碼排序
// 按數字大小排序
function foo(a,b){
	if (a>b){
		return 1;
	}else if (a<b){
		return -1;
	}else{
		return 0;
	}
}
a.sort(foo)		// --->得到按數字大小排序
function foo(a,b){
	return a-b
}

Date

//方法1:不指定參數
var d=new Date();
d.toLocaleString( );
//方法2:參數爲日期字符串
var d2=new Date("2019/01/01 00:00");
d2.toLocaleString( );
var d3=new Date("01/01/2019 00:00");
d3.toLocaleString( );
//方法3:參數爲毫秒數
var d3=new Date(1000);	// 在1970/1/1 8:00:00加1000毫秒,8點是因爲中國時間爲東八區
d3.toLocaleString( );
d3.toUTCString();	// unix發佈標準時間
//方法4:參數爲年月日小時分鐘秒毫秒
var d4=new Date(2019,1,1,00,00,0,100);
alert(d4.toLocaleString( ));
//毫秒不直接顯示
getDate()                 // 獲取日
getDay ()                 // 獲取星期
getMonth ()               // 獲取月(0-11)
getFullYear ()            // 獲取完整年份
getYear ()                // 獲取年
getHours ()               // 獲取小時
getMinutes ()             // 獲取分鐘
getSeconds ()             // 獲取秒
getMilliseconds ()        // 獲取毫秒
getTime ()                // 返回累計毫秒數(從1970/1/1午夜)

setDate(day_of_month)     // 設置日
setMonth (month)          // 設置月
setFullYear (year)        // 設置年
setHours (hour)    		  // 設置小時
setMinutes (minute)       // 設置分鐘
setSeconds (second)       // 設置秒
setMillliseconds (ms)     // 設置毫秒(0-999)
setTime (allms)           // 設置累計毫秒(從1970/1/1午夜)
getTimezoneOffset() // 返回本地時間與GMT的時間差,以分鐘爲單位
toUTCString();		// 返回國際標準時間字符串
toLocalString();	// 返回本地格式時間字符串
Date.parse(x);		// 返回累計毫秒數(從1970/1/1午夜到本地時間)
Date.UTC(x);		// 返回累計毫秒數(從1970/1/1午夜到國際時間)

RegExp正則

// 創建方法1
var re_obj=new RegExp('\d','g');//global參數
re_obj.test(str);	// 返回一個bool值,匹配成功返回true,失敗則返回false
//創建方法2
var re_obj2=/pattern/g;
re_boj2.test(str);

s.match(/pattern/g);	// 將所有匹配內容放入一個數組
s.search(/pattern/g);	// 得到第一個匹配結果的索引值

s.split(/pattern/g);	// 按pattern分割
s.replace(/old,new/g)

Math

內置對象,直接使用

Math.abs(n)    // 返回數的絕對值。
Math.exp(n)    // 返回 e 的指數。
Math.floor(n)  // 對數進行下舍入。
Math.log(n)    // 返回數的自然對數(底爲e)。
Math.max(n,m)    // 返回n和m中的最高值。
Math.min(n,m)    // 返回n和m中的最低值。
Math.pow(n,m)    // 返回n的m次冪。
Math.random()    // 返回 0 ~ 1 之間的隨機數。
Math.round(n)    // 把數四捨五入爲最接近的整數。
Math.sin(n)      // 返回數的正弦。
Math.sqrt(n)     // 返回數的平方根。
Math.tan(n)    	// 返回角的正切。

聲明提前

<script>
	function func1(){
		console.log(s);
		var s = 'string';
	}
	func1();
	// 在js的預編譯中,console.log(s);不會執行,但是找到var s時,會執行一次var s;而不會給s賦值,
	// 所以執行func1()會得到undefined;
</script>

BOM對象

與瀏覽器交互

Window對象

// 直接使用,不需要調用window.alert()
alert()            // 顯示帶有一段消息和一個確認按鈕的警告框。
confirm()          // 顯示帶有一段消息以及確認按鈕和取消按鈕的對話框。並根據選擇返回true or false;
prompt(str)           // 顯示可提示用戶輸入的對話框。參數可選,確認後返回輸入內容
open()             // 打開一個新的瀏覽器窗口或查找一個已命名的窗口。
close()            // 關閉瀏覽器窗口。
setInterval()      // 按照指定的週期(以毫秒計)來調用函數或計算表達式。
clearInterval()    // 取消由 setInterval() 設置的 timeout。
setTimeout()       // 在指定的毫秒數後調用函數或計算表達式。
clearTimeout()     // 取消由 setTimeout() 方法設置的 timeout。
scrollTo()         // 把內容滾動到指定的座標

一個html文檔對應一個窗口
控制窗口

Location對象

location.reload();	// 刷新,重載頁面
location.href(url);	// 跳轉網頁

History對象

// 前進/後退
history.forward();	// 上一個網頁
history.back();		// 下一個網頁
history.go(-1);		// 參數爲-1時,跳轉到上一網頁,爲1時,跳轉到下一網頁,0時爲當前網頁
history.length;		// 瀏覽器當前保存的網頁數

DOM對象(DHTML)

節點的方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
</head>
<body>
    <div id="div1">
        <div id="div2">div2</div>
        <p>p1</p>
    </div>

    <script >
        // 根據id獲取元素
        var ele=document.getElementById('div1');
        console.log(ele);                 // [object HTMLDivElement]
        console.log(ele.nodeName);        // DIV
        console.log(ele.nodeType);        // 1
        console.log(ele.nodeValue);       // null

        // 子元素
        var ele2=ele.firstChild;          // div1與div2中間的\t,\b
        console.log(ele2);                // #text
        console.log(ele2.nodeName);       // #text
        var ele3=ele.lastChild;
        console.log(ele3);                // #text
        console.log(ele3.nodeName);       // #text
        // 所有子元素
        var arr1=ele.childNodes;
        console.log(arr1.length);         // 5

        // 父標籤
        var ele4=ele.parentElement;
        console.log(ele4);                // <body>...</body>
        console.log(ele4.nodeName);       // BODY

        // 子標籤,加Element時,只找標籤中的元素
        var ele5=ele.firstElementChild;
        console.log(ele5);                // <div id='div2'>div2<div>
        var ele6=ele.lastElementChild;
        console.log(ele6);                // <p>p</p>
        var ele7=ele.children;
        console.log(ele7);                // HTMLCollection(2) [div#div2, p, div2: div#div2]
        console.log(ele7.length);         // 2
        for (var i=0;i<ele7.length;i++){
            console.log(ele7[i]);       // <div id='div2'>div2<div>     <p>p</p>
        }

        // 兄弟標籤
        var ele8=ele5.nextElementSibling;
        console.log(ele8);              // <p>p</p>
    </script>
</body>
</html>

尋找節點對象的方式

  1. 全局查找
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
</head>
<body>
    <div id="div1">
        <div class="div2" name="ht">div2</div>
        <div id="div3">div3</div>
        <p>p1</p>
        <div class="div2">div4</div>
    </div>

    <script >
        // 根據class查找,因爲class不唯一,Elements,結果爲一個數組
        var ele=document.getElementsByClassName('div2');
        console.log(ele);   // HTMLCollection(2) [div.div2, div.div2]
        // 獲取標籤中的文本
        console.log(ele[0].nextElementSibling.innerHTML);      // div3

        // 根據tag查找
        var tag=document.getElementsByTagName('p');
        console.log(tag);                   // HTMLCollection [p]
        console.log(tag[0].innerHTML);      // p1

        var n=document.getElementsByName('ht');
        console.log(n);                     // NodeList [div.div2]
        console.log(n[0].innerText);        // div2
    </script>
</body>
</html>
  1. 局部查找
<body>
    <div id="div1">
        <div class="div2" name="ht">div2</div>
        <div id="div3">div3</div>
        <p>p1</p>
        <div class="div2">div4</div>
    </div>
    <div id="div4">
        <p>p2</p>
    </div>

    <script >
        var div4=document.getElementById('div4');
        // 局部查找,
        var ele=div4.getElementsByTagName('p');
        console.log(ele[0].innerHTML);      // p2 // 只找到div4下的p標籤
    </script>
</body>

DOM Event(事件)

onclick();			// 單擊
ondblclick();		// 雙擊

onfocus();			// 元素獲得焦點
onblur();			// 元素失去焦點

onchange()			// 域內容改變

onkeydown()			// 鍵盤某個鍵被按下
onkeypress()		// 鍵盤某個鍵被按下並鬆開
onkeyup()			// 鍵盤某個鍵被鬆開
onload()			// 一張頁面或凸顯完成加載

onmousedown()		// 鼠標按鍵被按下
onmousemove()		// 鼠標移動
onmouseout()		// 鼠標從某個元素移開
onmouseover()		// 鼠標移動到某個元素上

onselect()			// 文本被選中
onsubmit()			// u企鵝人按鈕被點擊			

例子:

  1. 輸入框默認有內容,點擊輸入框後消失
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
</head>
<body>
    <p ondblclick="alert(123)">123</p>
    input: <input class='ky' type="text" name="input" value='input' onfocus="func1()" onblur="func2()">

    <script >
        function func1(){
            var ky=document.getElementsByClassName('ky')[0];		// 根據classname獲取input對象
            ky.value = '';		// 將input的value設置爲空
            // console.log(111)
        }
        function func2(){
            // console.log(222)
            var ky=document.getElementsByClassName('ky')[0];
            if (ky.value.trim().length===0){		// 去掉前後空格
                ky.value='input';
            }
        }
    </script>
</body>
</html>
  1. 按下、鬆開某個鍵時,觸發事件(οnkeydοwn=func(‘event’))
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
</head>
<body>
    <input type="button" onkeydown="func1(event)" onkeyup='func2(event)' value='press'>
    <script >
        function func1(e){
            if (e.keyCode===13){		// Enter=13;按下enter時觸發
                console.log(e.keyCode);
            }
        }
        function func2(e){
            if (e.keyCode===13){		// 鬆開Enter時觸發
                console.log(e.keyCode);
            }
        }
    </script>
</body>
</html>
  1. 頁面加載完成之後觸發
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <script >
        function func1(){
            var p1=document.getElementById('p1')
            alert(p1.nodeName)
        }
    </script>
</head>
<body onload="func1()">		<!--body加載完之後觸發-->
    <p id="p1">wolf</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <script >
        window.onload=function(){
            var p1=document.getElementById('p1');
            alert(p1.nodeName);
        }
    </script>
</head>
<body>
    <p id="p1">wolf</p>
</body>
</html>
  1. 鼠標事件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>
        div{
            background: #cc3399;
            width:100px;
            height:100px;
            line-height: 100px;
            text-align: center;
        }
    </style>
    <script >
        function func1(){		// 鼠標按下時觸發
            console.log('down')
        }
        function func2(){		// 鼠標鬆開時觸發
            console.log('up')
        }
        function func3(){		// 鼠標覆蓋時觸發
            console.log('over')
        }
        function func4(){		// 鼠標移開時觸發
            console.log('out')
        }
        function func5(){		// 鼠標移動時觸發
            console.log('move')
        }
    </script>
</head>
<body>
    <div onmousedown="func1()" onmouseup="func2()" onmouseover="func3()" onmouseout="func4()" onmousemove="func5()">wolf</div>
</body>
</html>
  1. 綁定事件的另外一種方式
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>
        div{
            background: #cc3399;
            width:100px;
            height:100px;
            line-height: 100px;
            text-align: center;
        }
    </style>
</head>
<body>
	<div id='div1'>wolf</div>
</body>
</html>
<script >
    var div1=document.getElementById('div1');
    div1.onclick=function(){			// 通過對象的方法來綁定事件
		alert(123);
	}
</script>
  1. 提交數據時觸發,只能綁定在form表單上
    方法1:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>
        div{
            background: #cc3399;
            width:100px;
            height:100px;
            line-height: 100px;
            text-align: center;
        }
    </style>
</head>
<body>
    <form id="form">
        <input type="text" name="name">
        <input type="submit" value="提交驗證">
    </form>
</body>
</html>
<script >
    var form1=document.getElementById('form');
    form1.onsubmit=function(){
        alert('驗證失敗');
        return false;			<// return false阻止提交數據;
    }
</script>

方法2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>
        div{
            background: #cc3399;
            width:100px;
            height:100px;
            line-height: 100px;
            text-align: center;
        }
    </style>
</head>
<body>
    <form id="form" onsubmit="return func1();">
        <input type="text" name="name">
        <input type="submit" value="提交驗證">
    </form>
</body>
</html>
<script >
    function func1(){
        alert('驗證失敗');
        return false;
    }
</script>

方法3:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>
        div{
            background: #cc3399;
            width:100px;
            height:100px;
            line-height: 100px;
            text-align: center;
        }
    </style>
</head>
<body>
    <form id="form" onsubmit="return func1(event);">
        <input type="text" name="name">
        <input type="submit" value="提交驗證">
    </form>
</body>
</html>
<script >
    function func1(event){
        alert('驗證失敗');
		event.prevnetDefault();		// 阻止傳輸數據
    }
</script>
  1. 阻止事件傳播
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>
        .div1{
            background: #cc3399;
            width:100px;
            height:100px;
        }
        .div2{
            background: black;
            width:50px;
            height: 50px;
        }
    </style>
</head>
<body>
    <div class="div1">
        <div class="div2"></div>
    </div>
</body>
</html>
<script >
    var div=document.getElementsByTagName('div');
    div[0].onclick=function(){
        alert(123);
    }
    div[1].onclick=function(){
        alert(234);
        event.stopPropagation()  // 阻止事件傳播,使點擊div2時不會觸發div1的點擊事件
    }
</script>

增刪改查

增刪改

createElement(name); 創建元素
appendChild();將元素添加到父標籤中
removeChild();將元素從父標籤中刪除

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>
        .div1{
            background: #cc3399;
            /*width:100px;*/
            height:50px;
            line-height: 50px;
        }
    </style>
</head>
<body>
    <div class="div1">
        <div class="div2">wolf1</div>
        <p>wolf2</p>
    </div>
    <form>
        <input type="button" value="添加" onclick="func1();">      <!--點擊觸發添加方法-->
        <input type="button" value="刪除" onclick="func2();">      <!--點擊觸發刪除-->
        <input type="button" value="大字" onclick="func3();">         <!--點擊觸發加粗-->
    </form>
</body>
</html>
<script >
    function func1() {
        var div1 = document.getElementsByClassName('div1')[0];       <!--父元素-->
        var son = document.createElement('p');                       <!--要添加的子元素和標籤-->
        son.innerHTML="<b>加粗字體</b>";                               <!--子元素的文本,能解析標籤,如果有標籤,按html標籤添加-->
        // son.innerText='<b>加粗字體</b>';                               <!--直接添加字符串,不解析-->
        son.style.color='red';				// 設置顏色
        son.style.font-size='39px';			// 設置字體大小
        son.name='p1';						// 設置name屬性
        // son.setAttribute('name','p1');	// 設置name屬性
        son.getAttribute('name');			// 獲取name屬性
        div1.appendChild(son);                                       <!--在父元素中添加子元素-->
    }
    function func2(){
        var div1 = document.getElementsByClassName('div1')[0];       <!--父元素-->
        var last_son = div1.lastElementChild;                        <!--最後一個子元素-->
        div1.removeChild(last_son);                                  <!--刪除子元素-->
    }
    function func3(){
        var div1=document.getElementsByClassName('div1')[0];        <!--找到div1標籤-->
        div1.style.fontSize='39px';                                 <!--設置字體大小-->
    }
</script>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>
        .div1{
            background: lime;
            /*width:100px;*/
            height:50px;
            line-height: 50px;
        }
        .bigger{
            color: #cc3399;
            font-size: 30px;
        }
        .small{
            color: dodgerblue;
            font-size: 15px;
        }
    </style>
</head>
<body>
    <div class="div1">
        <div class="div2">wolf1</div>
        <p>wolf2</p>
    </div>
    <form>
        <input type="button" value="大號字體" onclick="func('bigger');">      <!--點擊觸發添加方法-->
        <input type="button" value="原字體" onclick="func('small');">
    </form>
</body>
</html>
<script >
    function func(change) {
        var div1 = document.getElementsByClassName('div1')[0];       <!--父元素-->
        if (change==='bigger'){
            div1.classList.remove('small');
            div1.classList.add('bigger');
        }else{
            div1.classList.remove('bigger');
            div1.classList.add('small');
        }
    }
</script>


示例

示例1:點擊按鈕後出現小窗口操作,原頁面變背景,再點擊小窗口按鈕,回到原網頁。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>
		/*初始頁面*/
        .div1{
            position:fixed;
            width: 100%;
            height: 1000px;
            background-color: white;
        }
        /*點擊後變背景樣式*/
        .div1-1{
            background-color: darkgray;
        }
        /*點擊後出現的操作頁面樣式*/
        .div2{
            display: none;
            position: fixed;
            top:50%;
            left:50%;
            background-color: lime;
            width: 100px;
            height: 100px;
        }
        /*控制頁面顯示*/
        .div2-1{
            display: block;
        }
    </style>
</head>
<body>
    <div class="div1">
        <input type="button" class="input1" value="button">
        <div class="div2">
            <input type="button" class="input2" value="button">
        </div>
    </div>

</body>
</html>
<script >
    var inp1=document.getElementsByClassName('input1')[0];
    inp1.onclick=function(){
        var div1=document.getElementsByClassName('div1')[0];
        div1.classList.add('div1-1');
        var div2=document.getElementsByClassName('div2')[0];
        div2.classList.add('div2-1');
    };
    var inp2=document.getElementsByClassName('input2')[0];
    inp2.onclick=function(){
        var div1=document.getElementsByClassName('div1')[0];
        div1.classList.remove('div1-1');
        var div2=document.getElementsByClassName('div2')[0];
        div2.classList.remove('div2-1');
    };
</script>

示例2:二級菜單,第一集選擇後顯示二級

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>

    </style>
</head>
<body>
    <select id="province" onchange="func1(this)">
        
    </select>
    <select id="city">
        
    </select>
</body>
</html>
<script >
    var sel_pro=document.getElementById('province');	// 一級對象
    var sel_cit=document.getElementById('city');		// 二級對象
    data = {'重慶': ['渝北','江北'], '湖北':['武漢','襄陽'],'四川':['廣安','成都','南充']};
    for (var i in data){		// 遍歷字典時,i爲key
        var opt=document.createElement('option');		// 子標籤對象
        opt.innerHTML=i;					// 設置子元素文本
        sel_pro.appendChild(opt);			// 添加子元素
    }
    function func1(self){
        sel_cit.length=0;
        var province=self.options[self.selectedIndex].innerHTML;
        for (var i in data[province]){		// 遍歷數組時,i爲index
            var cit=document.createElement('option');
            cit.innerHTML=data[province][i];
            sel_cit.appendChild(cit);
        }
    }
</script>

示例3:左右選擇框的項目移動

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wolf</title>
    <style>
        .div1{
            display: inline-block;
            margin: 20px;
        }
    </style>
</head>
<body>
    <select id="left" multiple size="10">
        <option>籃球</option>
        <option>足球</option>
        <option>排球</option>
        <option>乒乓球</option>
        <option>拳擊</option>
        <option>體操</option>
    </select>
    <div class="div1">
        <input type="button" value="-->" onclick="to_right()"><br>
        <input type="button" value="=>" onclick="all_right()"><br>
        <input type="button" value="<--" onclick="to_left()"><br>
        <input type="button" value="<=" onclick="all_left()">
    </div>
    <select id="right" multiple size="10">
        <option>游泳</option>
        <option>擊劍</option>
        <option>健美</option>
        <option>羽毛球</option>
    </select>
</body>
<script>
    function to_right(){
        var sel_left=document.getElementById('left');
        var opt_left=sel_left.children;
        var sel_right=document.getElementById('right');
        for (var i=0;i<opt_left.length;i++){
            if (opt_left[i].selected===true){		// 判斷是否被選中
                opt_left[i].selected=false;			// 移動後取消選中
                sel_right.appendChild(opt_left[i--])		// 移動選項
            }
        }
    }
</script>
</html>

作用域

  1. 作用域基本與python一樣
  2. 不同的是js有一個先編譯,所有代碼會先編譯一遍再執行,導致同名函數會被覆蓋
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章