JavaScript高级 对象

1.    javascript中的对象分类

1.    自定义对象
2.    内置对象
3.    DOM对象
4.    BOM对象

1.    自定义对象

自己创建的对象就是自定义对象

当我们需要一种对象,可是javascript没有提供的时候,我们就需要自己动手定义我们需要的对象 

基本的2种自定义对象的创建方式 

1.    使用{}创建对象

var stu = {
    name: "苏",
	age: 21,
	address: "西安",
	getStuinfo: function() {
		return this.name + "-" + this.age + "-" + this.address;
	}
};

访问对象的属性

alert(stu.name + "," + stu.age + "," + stu.address);

访问对象的方法

var info = stu.getStuinfo();
alert(info);

2.    通过构造函数创建对象

声明定义函数

function stu() {
				this.name = "小";
				this.age = 21;
				this.address = "西安";
				this.getstuinfo = function() {
					return this.name + "-" + this.age + "-" + this.address;
				}
			}

创建对象

var stuobj = new stu();

访问对象的属性

alert(stuobj.name + "," + stuobj.age + "," + stuobj.address);

访问对象的方法

var info=stuobj.getstuinfo();
alert(info);

2.    内置对象

内置对象 :javascript语言本身提供的对象 

Number(数字)对象                 字符串(String) 对象               Math(算数)对象

Array(数组)对象     Date(日期) 对象      Boolean(布尔)对象    RegExp 对象

1.    Number对象

创建对象

var num1=new Number(100);
alert(typeof num1);//object类型
var num1=100;
alert(typeof num1);//number类型

1.    常见的属性和方法

关于进制的转换方法 

toString(参数[2,8,16]);

例如:

var num1=new Number(100);
alert(num1.toString(2));//1100100
var num1=new Number(100);
alert(num1.toString(8));//144
var num1=new Number(100);
alert(num1.toString(16));//64

isNaN() 全局函数来判断一个值是否是 NaN 值

var x = 1000 / "ccc";
alert(isNaN(x));//true 它不是一个数字
var x = 1000 / "1000";
alert(isNaN(x));//false 它是一个数字

Number.MAX_VALUE    最大值

alert(Number.MAX_VALUE);//1.7976931348623157e+308

Number.MIN_VALUE     最小值 

alert(Number.MIN_VALUE);//5e-324

Number.parseFloat()    将字符串转换成浮点数

var str1 = "52.1";
var number1 = Number.parseFloat(str1);
alert(number1);//52.1
alert(typeof number1);//number

Number.parseInt()    将字符串转换成整型数字

var str1 = "52";
var number1 = Number.parseInt(str1);
alert(number1);//52
alert(typeof number1);//number

toFixed 保留小数的位数

var i=1.77876333;
var val=i.toFixed(5);
alert(val);//1.77876

Infinity 无穷

var mynumber = 7;
			while (mynumber != Infinity) {
				mynumber = mynumber * mynumber;
				// alert(mynumber);
			}
			alert(mynumber);//Infinity
var sum = 10/0;
var sum1 = 1 - sum;
alert(sum1);//-Infinity

2.    字符串(String) 对象

创建对象

var str1=new String("xiao,nuan");

length 来计算字符串的长度

alert(str1.length);// 9

indexOf()  来定位字符串中某一个指定的字符首次出现的位置

alert(str1.indexOf("n"));// 5

lastIndexOf()  来定位字符串中某一个指定的字符最后一次出现的位置

alert(str1.lastIndexOf("n"));// 8

indexOf()  lastIndexOf() 定位的指定字符没有出现结果为 -1

alert(str1.indexOf("c"));// -1

match()  函数用来查找字符串中特定的字符,并且如果找到的话,则返回这个字符

alert(str1.match("su"));// null
alert(str1.match("xiao"));// xiao

replace()  方法在字符串中用某些字符替换另一些字符

alert(str1.replace("xiao,nuan","苏小暖"));// 苏小暖

字符串大小写转换使用函数

var str1 = new String("Su,Xiao,Nuan");

toUpperCase()  小写转换成大写 

alert(str1.toUpperCase());//SU,XIAO,NUAN

toLowerCase()  大写转换成小写

alert(str1.toLowerCase());//su,xiao,nuan

使用 split() 函数转为数组

var strarray = str1.split(",");
for (var i = 0; i < strarray.length; i++) {
				alert(strarray[i]);//Su Xiao Nuan
			}

charAt()  返回指定位置的字符

alert(str1.charAt(0));//S

includes()   查找字符串中是否包含指定的子字符串

alert(str1.includes("Su"));//true

startsWith()   查看字符串是否以指定的子字符串开头
endsWith()    查看字符串是否以指定的子字符串结尾

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var names = ["苏小暖", "小暖", "苏小梦", "苏筱梦", "小梦", "筱梦", "筱暖", "苏筱暖"];
			for (var i = 0; i < names.length; i++) {
				var name = names[i];
				if (name.startsWith("苏")) {
                //苏小暖 苏小梦 苏筱梦 苏筱暖
					alert(name);
				}
				if (name.endsWith("暖")) {
                //苏小暖 小暖 筱暖 苏筱暖
					alert(name);
				}
			}
		</script>
	</head>
	<body>
	</body>
</html>

substr (起始索引号,指定数目)   从起始索引号提取字符串中指定数目的字符

substring(起始索引号,结束索引号)    提取字符串中两个指定的索引号之间的字符

var str1="su,xiao,nuan";
alert(str1.substr(0,2)); //su
alert(str1.substring(3,str1.length));//xiao,nuan

trim()   去除字符串两边的空白

var str="   su,xiao,nuan   ";
alert(str.length);//18
var newstr=str.trim();
alert(newstr.length);//12

字符串中的转义字符【特殊字符】

转义字符:  \"--双引号  \'--单引号  \\--斜杆  \n--换行  \r--回车 \r\n--回车换行 \t--tab \b--空格

alert("\"\t f:\\\r\nlianxi.html\b\"");

valueOf()    返回某个字符串对象的原始值

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var str1 = new String("xiao");
			var str2 = str1.valueOf();
			alert(typeof str1);//object
			alert(typeof str2);//string
		</script>
	</head>
	<body>
	</body>
</html>

toString()   返回一个字符串

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var str1 = new String("xiao");
			var str2 = str1.toString();
			alert(typeof str1);//object
			alert(typeof str2);//string
		</script>
	</head>
	<body>
	</body>
</html>

3.   Date(日期) 对象

new Date();  得到当前系统时间

var date=new Date()
alert(date);//Sat Sep 04 2021 10:48:54 GMT+0800 (中国标准时间)

new Date(毫秒数)

var date=new Date(1000); //从1970年1月1日0时0点0分开始向后推进指定参数的毫秒数
alert(date);//Thu Jan 01 1970 08:00:01 GMT+0800 (中国标准时间)

new Date(dateString);  通过指定格式的字符串创建日期对象

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var date=new Date("2000/8/25 05:20");
			alert(date);//Fri Aug 25 2000 05:20:00 GMT+0800 (中国标准时间)
		</script>
	</head>
	<body>
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var date=new Date("2000-8-25 05:20");
			alert(date);//Fri Aug 25 2000 05:20:00 GMT+0800 (中国标准时间)
		</script>
	</head>
	<body>
	</body>
</html>

以上俩种格式是正确的,下面这种不可取

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var date=new Date("2000年8月25日 05点20分");
			alert(date);//Invalid Date
		</script>
	</head>
	<body>
	</body>
</html>

Invalid Date 无法得到

通过指定年月日时分秒的数字值创建日期对象,月份减1

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var date = new Date("2000", "07", "25", "05", "20");
			alert(date);//Fri Aug 25 2000 05:20:00 GMT+0800 (中国标准时间)
		</script>
	</head>
	<body>
	</body>
</html>

创建的时间日期的方法

getFullYear()	//从 Date 对象以四位数字返回年份。
getMonth()	//从 Date 对象返回月份 (0 ~ 11)。
getDate()	//从 Date 对象返回一个月中的某一天 (1 ~ 31)。
getHours()	//返回 Date 对象的小时 (0 ~ 23)。
getMinutes()	//返回 Date 对象的分钟 (0 ~ 59)。
getSeconds()	//返回 Date 对象的秒数 (0 ~ 59)。
getDay()	//从 Date 对象返回一周中的某一天 (0 ~ 6)。
getTime()	//返回 1970 年 1 月 1 日至今的毫秒数。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var date1=new Date(); 
			var fullYear=date1.getFullYear();
			var month=date1.getMonth();
			var date=date1.getDate();
			var hours=date1.getHours();
			var minutes=date1.getMinutes();
			var seconds=date1.getSeconds();
			var day=date1.getDay();
            //2021年9月4日 11时12分24秒 星期六
			alert(fullYear+"年"+(month+1)+"月"+date+"日"+hours+"时"+minutes+"分"+seconds+"秒 星期"+day);
		</script>
	</head>
	<body>
	</body>
</html>
setDate()	//设置 Date 对象中月的某一天 (1 ~ 31)。
setFullYear()	//设置 Date 对象中的年份(四位数字)。
setHours()	//设置 Date 对象中的小时 (0 ~ 23)。
setMilliseconds()	//设置 Date 对象中的毫秒 (0 ~ 999)。
setMinutes()	//设置 Date 对象中的分钟 (0 ~ 59)。
setMonth()	//设置 Date 对象中月份 (0 ~ 11)。
setSeconds()	//设置 Date 对象中的秒钟 (0 ~ 59)。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var date1=new Date();
			date1.setFullYear("2000");
			var fullYear=date1.getFullYear();
			alert(fullYear);//2000
		</script>
	</head>
	<body>
	</body>
</html>

getTime()    返回 1970 年 1 月 1 日至今的毫秒数     new Date(毫秒数);

alert(new Date().getTime()); //1630725556374

4.    Array(数组) 对象 

数组对象是使用单独的变量名来存储一系列的值 

new Array([参数]);
参数  一个数字  数组的存储空间 

没有指定存储空间的空数组 

var arr1 = new Array();

指定5个存储空间的空数组 

var arr2 = new Array(5);

创建数组对象

var myCars=new Array("Saab","Volvo","BMW");
alert(typeof myCars);//object
var myCars=["Saab","Volvo","BMW"];
alert(typeof myCars);//object

先创建后赋值 需要下标

var test=new Array(3);
test[0]="xiaonuan";
test[1]="21";
test[2]="xiaonuan";
test[3]="21";
test[4]="xiaonuan";
test[5]="21";

注意: new Array(3)指定数组空间的情况

alert(test.length);//6
var test=new Array(3);
test[0]="xiaonuan";
test[1]="21";
alert(test.length);//3

可以知道元素超过数组给定空间,空间大小为元素数量

未超出给定空间,空间大小为给定空间大小

1.    concat()  属性 合并数组

var myCars=["Saab","Volvo","BMW"];
var test=["xiaonuan","xiaomeng"];
var newarray=myCars.concat(test);
for (var index in newarray) {
    //依次输出五个元素
	alert(newarray[index]);
}
alert(newarray.length);//5

2.    forEach() 属性 

数组每个元素都执行一次回调函数 

var myCars=["Saab","Volvo","BMW"];
var test=["xiaonuan","xiaomeng"];
var newarray=myCars.concat(test);
newarray.forEach(function(element){
    //依次输出五个元素
	alert(element);
});

3.    includes() 属性 

判断一个数组是否包含一个指定的值 

var myCars=["Saab","Volvo","BMW"];
var test=["xiaonuan","xiaomeng"];
var newarray=myCars.concat(test);
alert(newarray.includes("xiaonuan"));//true
alert(newarray.includes("su xiao"));//false

indexOf()  搜索数组中的元素,并返回它所在的位置

lastIndexOf()  搜索数组中的元素,并返回它最后出现的位置

join()  把数组的所有元素放入一个字符串 参数为元素间的 “,” 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var myCars=["Saab","Volvo","BMW"];
			var test=["xiaonuan","xiaomeng","xiaonuan","xiaomeng"];
			var newarray=myCars.concat(test);
            alert(newarray.indexOf("xiaonuan"));//3
			alert(newarray.lastIndexOf("xiaonuan"));//5
            //输出结果Saab,Volvo,BMW,xiaonuan,xiaomeng
            alert(newarray.join(","));
		</script>
	</head>
	<body>
	</body>
</html>

4.    push()  unshift()  属性   

push()  向数组的末尾添加一个或更多元素,并返回新的长度  

unshift()  向数组的开头添加一个或更多元素,并返回新的长度 

var myCars=["Saab","Volvo","BMW"];
var test=["xiaonuan","xiaomeng"];
var newarray=myCars.concat(test);
alert(newarray.push("wei"));//6
alert(newarray.unshift("su"));//7

5.    slice(开始下标,结束下标)  

选取数组的一部分,并返回一个新数组

var myCars=["Saab","Volvo","BMW"];
var test=["xiaonuan","xiaomeng"];
var newarray=myCars.concat(test);
//参数为数组下标
var arr=newarray.slice(0,5);
alert(arr);//Saab,Volvo,BMW,xiaonuan,xiaomeng

6.    sort()    

对数组的元素进行排序 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var  numarr=[111,333,222,555,444];
			//从小到大排列 111,222,333,444,555
			alert(numarr.sort(function(a,b){return a-b;}));
			//从大到小排列 555,444,333,222,111
			// alert(numarr.sort(function(a,b){return b-a;}));
		</script>
	</head>
	<body>
	</body>
</html>

7.    toString()    

把数组转换为字符串,并返回结果

var testCars=["Saab","Volvo","BMW"];
var str=testCars.toString();
alert(str);//Saab,Volvo,BMW
alert(typeof str);//string

5.    Boolean(布尔) 对象

toString()    把布尔值转换为字符串,并返回结果 

valueOf()    返回 Boolean 对象的原始值

var boo1 = new Boolean(true);//创建布尔对象
alert(typeof boo1);//object
var boo2 = boo1.toString();
alert(typeof boo2);//string
var boo3 = boo1.valueOf();
alert(typeof boo3);//boolean

注意事项 :
             var num1=10;      0==false                  非0数字---true
             var str="new";     空字符串==false     非空字符串==true 
             var test1=null;     null==false

举例 

var test = 1;
if (test) {
     alert(true);//true
}else{
     alert(false);//false
} 

6.    Math(算数) 对象

Math(算数)对象 调用一些数学运算相关的属性和方法

不需要创建对象 Math就是对象 

E  返回算术常量 e 

PI  返回圆周率 Π

max(x,y,z,...,n)    返回 x,y,z,...,n 中的最高值

min(x,y,z,...,n)    返回 x,y,z,...,n中的最低值 

round(x)    四舍五入 

正数 round(x)    四舍五入
负数 round(x) 无限接近的整数 

random()    返回 0 ~ 1 之间的随机数 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			alert(Math.E);//2.718281828459045
			alert(Math.PI);//3.141592653589793
			alert(Math.max(111,222,333,555));//555
			alert(Math.min(111,222,333,555));//111
			alert(Math.round(5.5)); //6
			alert(Math.round(-5.5)); //-5
			alert(Math.random());//0.00000000001 -- 1
		</script>
	</head>
	<body>
	</body>
</html>

7.    RegExp 对象 

正则表达式描述了字符的模式对象,实际上就是一个用于查找/匹配字符串的规则
正则表达匹配字符

1.RegExp对象
var patt=new RegExp(pattern,modifiers);
var patt=/pattern/modifiers;
注意前后的“/”
var patt=new RegExp(/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/);
alert(patt.test("18066527652"));

2.String中的match可以检索正则表达 -- 不常用
alert("qesgdasf".match(/[a-z]{5}/)); 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function getSms() {
				//得到文本框中输入的手机号码
				var phone = document.getElementById("input").value;
				//创建正则表达式对象
				var patt = new RegExp(/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/);
				//匹配手机号码
				if (patt.test(phone)) {
					alert("验证码:876543");
				} else {
					alert("手机号码有误!");
				}
			}
		</script>
	</head>
	<body>
		<input type="text" id="input" />
		<input type="button" value="发送验证码" onclick="getSms();" />
	</body>
</html>

8.    DOM 对象 

DOM     Document Object Model[文档对象模型]
当网页被加载时,浏览器会创建页面的文档对象模型

 

1.JavaScript 能够改变页面中的所有 HTML 元素

2.JavaScript 能够改变页面中的所有 HTML 属性

3.JavaScript 能够改变页面中的所有 CSS 样式

4.JavaScript 能够对页面中的所有事件做出反应

想要完成上面的4个功能的操作,我们就需要得到自己需要控制的html元素

通过文档对象模型提供的方法得到的html元素,我们就认为它是DOM对象

1.getElementById(id属性值);通过 id 查找 HTML 元素

2.getElementsByTagName(标签名)通过标签名查找 HTML 元素

3.getElementsByClassName(class属性值)通过类名找到 HTML 元素

1.    ID得到/修改DOM对象

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function test1() {
				var bycol = document.getElementById("p1");
				alert(bycol);//[object HTMLParagraphElement]
				bycol.style.color = "#f40";
			}
		</script>
	</head>
	<body>
		<p id="p1">这是一个段落</p>
		<p id="p1">这是一个段落</p>
		<p id="p1">这是一个段落</p>
		<input type="button" value="测试getElementById(id属性值)" onclick="test1();">
	</body>
</html>

getElementById(id属性值);  通过 id 查找 HTML 元素 

当id的属性值相同的时候,只能得到第一个元素

2.    元素得到/修改DOM对象

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function test1() {
				var bycol = document.getElementsByTagName("p");
				alert(bycol);//[object HTMLCollection]
				bycol[0].style.color = "#f40";
				bycol[1].style.backgroundColor = "#f40";
				bycol[2].style.fontSize = "30px";
			}
		</script>
	</head>
	<body>
		<p>这是一个段落</p>
		<p>这是一个段落</p>
		<p>这是一个段落</p>
		<input type="button" value="测试getElementsByTagName(标签名)" onclick="test1();">
	</body>
</html>

getElementsByTagName(标签名); 通过标签名查找 HTML 元素

注意: getElementsByTagName(标签名)得到一个DOM对象数组,哪怕只有一个元素依然是数组

3.    class得到/修改DOM对象

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	    <script type="text/javascript">
	    	function test1(){
				var bycol = document.getElementsByClassName("cla");
				alert(bycol);//[object HTMLCollection]
				bycol[0].style.color="#f40";
				bycol[1].style.backgroundColor="#f40";
				bycol[2].style.fontSize="30px";
			}
	    </script>
	</head>
	<body>
		<p class="cla">这是一个段落</p>
		<p class="cla">这是一个段落</p>
		<p class="cla">这是一个段落</p>
		<input type="button" value="测试getElementsByClassName(class属性值)" onclick="test1();">
	</body>
</html>

getElementsByClassName(class属性值)通过类名找到 HTML 元素

注意:  getElementsByClassName(class属性值)得到一个DOM对象数组,哪怕只有一个元素依然是数组 

4.    得到/修改html元素

得到/修改html元素/html元素中的文本内容 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
		    function testinner(){
		    	var  pobj1=document.getElementById("p1"); 	
                //会得到html元素的文本内容,可以得到包含在html元素中的html标记的文本
                var text2=pobj1.innerHTML;
		    	alert(text2);
		    	var  input1=document.getElementById("input1");
		    	var text3=input1.value;  //得到表单元素的文本内容。
		    	alert(text3);
		    }
			function updateinner(){
				var  pobj2=document.getElementById("p2");
				// pobj2.innerHTML="修改<a href='#'>html</a>元素中的文本内容";  
                //在输出内容的时候,如果有html标记,会被解释运行。
				var  input2=document.getElementById("input2");
				input2.value="神里流,霜灭";  //修改表单元素的文本内容。	
			}
		</script>
	</head>
	<body>
		<p id="p1">得到<a href="#">html</a>元素中的文本内容</p>
		<input id="input1" type="text" /><br>
		<input type="button" value="inner" onclick="testinner();">
		<p id="p2">修改html元素中的文本内容</p>
		<input id="input2" type="text" /><br>
		<input type="button" value="测试修改元素的文本内容" onclick="updateinner();">
	</body>
</html>

5.    得到/修改html元素的属性

得到html元素的属性:dom对象.属性名称 

修改html元素的属性:dom对象.属性名称="新的属性值"

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function getAttr(){
				var imgarray=document.getElementsByTagName("img");
				var srcvalue=imgarray[0].src;//得到属性
				alert(srcvalue);//file:///F:/wangxing/lianxi/20210907JavaScript/imgs/sx.png
				imgarray[0].src="imgs/sxm.jpg";//得到后修改属性值
			}
		</script>
	</head>
	<body>
		<img src="imgs/sx.png" /><br>
		<input type="button" value="得到html元素的属性" onclick="getAttr();"><br>
	</body>
</html>

以上得到了 img 元素中的 src 属性,并修改属性值

注意:以上为HTML属性修改方法,非CSS属性修改 

6.    得到/修改html元素的CSS的属性值

修改css属性,display属性 隐藏 / 显示

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function testcss1() {
				var imgarray = document.getElementsByTagName("img");
				var val = imgarray[0].style.display;
				if (val == "block") {
					//修改CSS的属性:dom对象.style.属性名称="属性值"
					imgarray[0].style.display = "none";
				} else {
					imgarray[0].style.display = "block";
				}
			}
		</script>
	</head>
	<body>
		<img src="imgs/sx.png" style="border:10px solid red;display:block;" /><br>
		<input type="button" value="测试css" onclick="testcss1();">
	</body>
</html>

以上输出结果为,图片默认显示,点击按钮后隐藏

注意:  上面的css控制方式,只使用与行内样式控制

使用obj.style.cssText 来修改嵌入式的css

修改css属性,border 边框属性得颜色

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.img2 {
				width: 100px;
				height: 100px;
				border: 10px solid black;
			}
		</style>
		<script type="text/javascript">
			function testcss2() {
				var imgarray = document.getElementsByClassName("img2");
				//使用obj.style.cssText 来修改嵌入式的css
				imgarray[0].style.cssText="width:100px;height:100px;border:10px solid #F40;";
			}
		</script>
	</head>
	<body>
		<img class="img2" src="imgs/sx.png" /><br>
		<input type="button" value="测试控制css" onclick="testcss2();">
	</body>
</html>

点击按钮后,边框颜色由黑色变为红色

使用  imgobj.setAttribute("class","img2"); 与 imgobj.className="img2";来修改嵌入式的css

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.img2{
				width:100px;
				height:100px;
				border:10px solid blue;
			}
		</style>
		<script type="text/javascript">
			function testcss3(){
				var imgobj=document.getElementById("img1");
				//俩种改变属性得方式
				imgobj.setAttribute("class","img2");
				// imgobj.className="img2";
			}
		</script>
	</head>
	<body>
		<img id="img1"  src="imgs/sx.png" /><br>
		<input type="button" value="测试控制css" onclick="testcss3();">
	</body>
</html>

上述代码给未添加css样式得图片添加了样式

7.    JavaScript 能够控制事件

页面初始化事件 通过window对象调用onload事件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			//通过window对象调用onload事件
			window.onload=function(){
				alert("页面初始化事件");//页面初始化事件
			}
		</script>
	</head>
	<body>
	</body>
</html>

页面打开后弹出 

按钮点击事件 onclick 属性

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			function  testClick(){
				alert("按钮点击事件");//按钮点击事件
			}
		</script>
	</head>
	<body>
		<input type="button" value="测试按钮点击事件" onclick="testClick();"/>
	</body>
</html>

点击按钮后弹出

使用 getElementById 测试按钮点击事件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			window.onload=function(){
				var  but1=document.getElementById("but1");//object HTMLInputElement
				but1.onclick=function(){
					alert("按钮点击事件");//按钮点击事件
				}
			}
		</script>
	</head>
	<body>
		<input id="but1" type="button" value="测试按钮点击事件" />
	</body>
</html>

点击按钮后弹出

onfocus当获得焦点时触发
onblur当失去焦点时触发

方式1:在按钮的开始标记中设置onfocus/onblur属性绑定函数
方式2:在页面初始化事件中得到文本框的dom对象.οnfοcus=function(){}/文本框的dom对象.οnblur=function(){}

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			window.onload=function(){
				var testObj1 = document.getElementById("test1");
				testObj1.onfocus = function() {
					testObj1.value = "";//聚焦时文本清空
				}
				testObj1.onblur = function() {
					alert(testObj1.value);//失去焦点时保存输入文本
				}
			}
		</script>
	</head>
	<body>
		<input id="test1" type="text" value="测试文本框的聚焦/失焦">
	</body>
</html>

onmouseover鼠标进入 和 onmouseout鼠标移开 事件 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			window.onload=function(){
				var imgObj1 = document.getElementById("img1");
				imgObj1.onmouseover=function(){
					imgObj1.width="200";
					imgObj1.height="200";
				}
				imgObj1.onmouseout=function(){
					imgObj1.width="100";
					imgObj1.height="100";
				}
			}
		</script>
	</head>
	<body>
		<img id="img1" src="imgs/sx.png" width="100px" height="100px">
	</body>
</html>

鼠标移动到图片上时,图片放大,鼠标移走后图片恢复原大小

onsubmit 只能作用在表单上  绑定执行函数的时候前面需要return xxxx();

被绑定的函数的返回值一定是boolean值,true--提交表单数据   false---不提交表单数据 

onsubmit 事件会在表单中的确认按钮【submit】被点击时发生 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			window.onload = function() {
				function testsubmit() {
					alert("表单提交事件!");
					return false;
				}
			}
		</script>
	</head>
	<body>
		<form action="login" method="get" onsubmit="return testsubmit();">
			<input type="text" name="username" /><br>
			<input type="password" name="password" /><br>
			<input type="submit" value="登陆" />
		</form>
	</body>
</html>

 

可以看到表单在点击登录后会向后端处理程序提交请求 

注意:按钮只可以用 submit 提交

onkeydown 事件会在用户按下一个键盘按键时发生 

被绑定的处理函数需要一个 event 参数
event 参数有一个属性 keyCode, 得到键盘按键对应的数字
onkeydown 事件往往作用在 body 元素上

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function testkey(event){
				var code=event.keyCode;
				if(code==37){
					alert("向左");
				}
				if(code==38){
					alert("向上");
				}
				if(code==39){
					alert("向右");
				}
				if(code==40){
					alert("向下");
				}
				if(code==13){
					alert("暂停");
				}
			}	
		</script>
	</head>
	<body onkeydown="testkey(event);">
	</body>
</html>

 我们按 "上键" "下键" "左键" "右键" "回车键" 都回弹出对应得 "上" "下" "左" "右" "暂停"

创建元素

appendChild 创建元素 (子元素的dom对象)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
		   #div1{
				width: 500px;
				height: 500px;
				background-color: yellow;
		   }
		</style>
		<script>
			function createEle(){
				//创建html元素 "a"
				var aobj=document.createElement("a");
				//创建元素"a"中的文本内容
				var atext=document.createTextNode("这是一个超链接");
				//向父元素中追加元素
				aobj.appendChild(atext);
				//向元素"a"中添加空链接
				aobj.href="#";
				//元素"a"中添加属性
				aobj.style.fontSize="30px";
				//通过 getElementById 得到父元素保存
				var divobj1=document.getElementById("div1");
				//父元素的dom对象.appendChild(子元素的dom对象)
				divobj1.appendChild(aobj);
			}
		</script>
	</head>
	<body>
		<div id="div1">	
		</div>
		<input type="button"  value="创建html元素" onclick="createEle();" />
	</body>
</html>

点击一次按钮就可以创建一个子元素链接

 

9.    BOM对象 

JavaScript中的BOM对象 

BOM   Browser Object Model 浏览器对象模型

window 对象是BOM的主要对象
window 对象中的主要属性:确定浏览器窗口的尺寸
window 对象中的主要方法:打开/关闭窗口的控制方法 / 各种操作弹框
window 对象中的主要子对象:Screen屏幕子对象 / Location url子对象 / History历史子对象 / Navigator浏览器子对象

 

1.    控制浏览器窗口尺寸的属性

window.onload = function() {
				var  w=window.innerWidth; //浏览器窗口的内部宽度
				var  h=window.innerHeight; //浏览器窗口的内部高度
                alert(w + "*" +h);
}

不包括工具栏和滚动条

window.onload = function() {
	// var  w=document.documentElement.clientWidth;
	// var  h=document.documentElement.clientHeight;
    alert(w + "*" +h);//1280*609
	var  w=document.body.clientWidth;
	var  h=document.body.clientHeight;
    alert(w + "*" +h);//1264*0
}

实用的 JavaScript 方案(涵盖所有浏览器) 

<script type="text/javascript">
	var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	var h=window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
	alert(w +" * "+ h);
</script>

 

2.    打开/关闭窗口的控制方法

window.open(URL,name,features,replace)
URL   一个可选的字符串,声明了要在新窗口中显示的文档的 URL
name   一个可选的字符串,该字符声明了新窗口的名称,这个名称可以用作标记 a 和 form 的属性 target 的值
features   一个可选的字符串,声明了新窗口要显示的标准浏览器的特征
replace   一个可选的布尔值, true - URL 替换浏览历史中的当前条目。false - URL 在浏览历史中创建新的条目。 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function openjavascript1() {
				// window.open("javascript1.html", "HTML标题", "width=500,height=500", true);
				window.open("http://www.baidu.com");
			}
		</script>
	</head>
	<body>
		<input type="button"value="点击打开新页面" onclick="openjavascript1();" />
	</body>
</html>

效果等同于超链接,打开新页面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>第一个网页</title>
		<script type="text/javascript">
			function closejavascript(){
				window.close();
			}
		</script>
	</head>
	<body>
		<h1>第一个网页</h1>
		<input type="button" value="点击关闭网页"onclick="closejavascript();" /><br>
	</body>
</html>

点击关闭本页面

3.    JavaScript 弹窗方法 

警告框 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function testalert(){
				alert("警告框");
			}
		</script>
	</head>
	<body>
		<input type="button" value="警告框" onclick="testalert();"/>
	</body>
</html>

确认框

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function testconfirm(){
				confirm("确认框,你确定关闭页面吗?");
				if(confirm){
					window.close();
				}
			}
		</script>
	</head>
	<body>
		<input type="button" value="确认框" onclick="testconfirm();"/>
	</body>
</html>

提示框

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function testprompt() {
				var styprompt = prompt("请输入你喜欢的孩子。", "比如'男朋友'");
				if (styprompt != null) {
					alert(styprompt.substring(0, styprompt.length));
				}
			}
		</script>
	</head>
	<body>
		<input type="button" value="提示框" onclick="testprompt();" />
	</body>
</html>

 

4.    screen屏幕子对象 

1. 总宽度和总高度  screen.width   /  screen.height

<script type="text/javascript">
	window.onload=function(){
		var  zongw=window.screen.width;
		var  zongh=window.screen.height;
		document.write(""+zongw+"*"+zongh+"");
	}
</script>

2. 可用宽度和可用高度  screen.availWidth  / screen.availHeight

<script type="text/javascript">
	window.onload=function(){
		var  availw=window.screen.availWidth;
		var  availh=window.screen.availHeight;
		document.write(""+availw+"*"+availh+"");
	}
</script>

3. 色彩深度  screen.colorDepth  色彩分辨率  screen.pixelDepth 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			var  colorDepth=window.screen.colorDepth;
			var  pixelDepth=window.screen.pixelDepth;
			document.write("色彩深度=="+colorDepth+"<br />");
			document.write("色彩分辨率=="+pixelDepth+"");		
		</script>
	</head>
	<body>
	</body>
</html>

 

5.    Location url子对象 

location.href 属性返回当前页面的 URL 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			function testhref(){
				var url1=window.location.href;
				alert(url1);//file:///F:/wangxing/lianxi/20210908JavaScript)/lianxi4-2.html
				window.location.href="javascript1.html";
			}
		</script>
	</head>
	<body>
		<input type="button" value="testhref" onclick="testhref();"/>
	</body>
</html>

location.search 属性是一个可读可写的字符串,可设置或返回当前 URL 的查询部分(问号 ? 之后的部分)

window.onload = function() {
var query = window.location.search;
alert(query);//?username=mingzi&password=333
}

 

6.    window History 历史对象 

history.back()  与在浏览器点击后退按钮相同
history.forward()  与在浏览器中点击按钮向前相同

例子 三个文档的切换 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>第一个网页</title>
		<script>
			function testforward() {
				window.history.forward();
			}
		</script>
	</head>
	<body>
		<h1>第一个网页</h1>
		<a href="javascript2.html">
			<input type="button" value="javascript2.html -->" onclick="testforward();">
		</a><br>
	</body>
</html>

点击向后按钮切换 javascript 2 .html 文件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>第二个网页</title>
		<script>
			function testback() {
				window.history.back();
			}
		</script>
		<script>
			function testforward() {
				window.history.forward();
			}
		</script>
	</head>
	<body>
		<h1>第二个网页</h1>
		<a href="javascript1.html">
			<input type="button" value="javascript1.html <--" onclick="testback();">
		</a><br>
		<a href="javascript3.html">
			<input type="button" value="javascript3.html -->" onclick="testforward();">
		</a><br>
	</body>
</html>

点击向前按钮切换 javascript 1 .html 文件 

点击向后按钮切换 javascript 3 .html 文件 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>第三个网页</title>
		<script>
			function testback() {
				window.history.back();
			}
		</script>
	</head>
	<body>
		<h1>第三个网页</h1>
		<a href="javascript2.html">
			<input type="button" value="javascript2.html <--" onclick="testback();">
		</a>
	</body>
</html>

点击向前按钮切换 javascript 2 .html 文件 

 

7.    window Navigator 浏览器的信息

<script>
	window.onload=function(){
		document.write("<h1>浏览器代号:"+window.navigator.appCodeName+"</h1>");
		document.write("<h1>浏览器名称:"+window.navigator.appName+"</h1>");
		document.write("<h1>浏览器版本:"+window.navigator.appVersion+"</h1>");
		document.write("<h1>启用Cookies:"+window.navigator.cookieEnabled+"</h1>");
		document.write("<h1>硬件平台:"+window.navigator.platform+"</h1>");
		document.write("<h1>用户代理:"+window.navigator.userAgent+"</h1>");
		document.write("<h1>用户代理语言:"+window.navigator.systemLanguage+"</h1>");
	}
</script>

 

8.    JavaScript 计时事件 

setInterval()  间隔指定的毫秒数不停地执行指定的代码

参数1 指定的运行代码是一个function
参数2 指定的毫秒数
clearInterval(intervalVariable) 方法用于停止 setInterval() 方法执行的函数代码。
intervalVariable参数是 setInterval() 的返回值
setTimeout() 方法--间隔指定的毫秒数执行指定的代码一次
参数1 指定的运行代码是一个function
参数2 指定的毫秒数
clearTimeout(timeoutVariable) 方法用于停止执行 setTimeout() 方法的函数代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			span {
				font-size: 30px;
				font-weight: bold;
				line-height: 50px;
				padding: 10px;
				margin: 10px;
			}
		</style>
		<script>
			//创建时间日期对象
			function getDate() {
				var date1 = new Date();
				var strdate1 = date1.getFullYear() + "年" + (date1.getMonth() + 1) + "月" +
					date1.getDate() + "日 " + date1.getHours() + ":" + date1.getMinutes() + ":" + date1.getSeconds();
				document.getElementById("dat").innerText = strdate1;
			}
			var res = null;
			function start() {
				res = setInterval(function() {
					getDate();
				}, 1000);
			}
			function end() {
				clearInterval(res);
			}
		</script>
	</head>
	<body>
		<span>时间:</span><span id="dat">&nbsp;</span><br>
		<input type="button" value="开始计时" onclick="start();" />
		<input type="button" value="停止计时" onclick="end();" />
	</body>
</html>

猜数字游戏

猜1~100之间的数字,猜到后结束

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script>
			var num1 = parseInt(Math.random() * 100 + 1);
			function cai() {
				var mynum = document.getElementById("input").value * 1;
				var i = 1;
				if (isNaN(mynum)) {
					alert("不是数字请重新输入!")
					document.getElementById("input").value = "";
				} else {
					if (mynum >= 1 && mynum <= 100) {
						if (mynum > num1) {
							alert("猜大了!");
							document.getElementById("input").value = "";
						}
						if (mynum < num1) {
							alert("猜小了!");
							document.getElementById("input").value = "";
						}
						if (mynum == num1) {
							alert("猜对了!GameOver");
							window.close();
						}
					} else {
						alert("输入的数字不在范围内,请重新输入!")
						document.getElementById("input").value = "";
					}
				}
			}
		</script>
	</head>
	<body>
		<input type="text" id="input" />
		<input type="button" value="猜数字游戏" onclick="cai();" />
	</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值