JavaScript核心(三)

1.1 今日目标

  1. 能够说出js中常见的系统对象
  2. 能够查阅系统对象的常用方法
  3. 能够创建节点并添加到页面中
  4. 能够完成节点的替换,删除,克隆操作
  5. 能够获取元素的属性节点
  6. 能够修改或添加元素的属性节点
  7. 能够获取和设置元素的css样式
  8. 能够用多种方法获取(查找)页面中的节点
  9. 能够说出至少10个以上的事件名称
  10. 能够说出3种事件绑定方式及其区别
  11. 能够理解事件冒泡及捕获的过程,并能阻止冒泡事件

1.2 事件

1.2.1 简介

鼠标、键盘所发生的动作就是事件,事件有onclick、onmouseover、onmouseout等等

事件发生需要有事件处理,该处理称为“事件处理”,事件处理通常由函数来执行。

1.2.2 DOM1级事件

1、添加DOM1级事件

事件以onclick为例:

方法一:行内绑定
<input type="button"  onclick='事件处理函数()' >
方法二:行内绑定
<input type="button"  onclick='函数体' >
方法三:动态绑定
node.onclick=function(){
}
方法四:动态绑定
node.onclick=函数名

2、取消DOM1级事件

node.onclick=null

3、例题:点击按钮,只能弹出一次对话框

<script>
window.onload=function(){
	document.getElementById('btn').onclick=function(){
		alert('锄禾日当午');
		this.onclick=null;	//取消事件绑定
	}
}
</script>
<input type="button" value="点击" id='btn'>
1.2.2 DOM2级事件

1、添加DOM2级事件

注意:DOM2级事件中没有’on’

<input type="button" value="点击" id='btn'>
<script>
window.onload=function(){
	//DOM2级绑定
	document.getElementById('btn').addEventListener('click', function(){
		alert('锄禾日当午');
	});
}
</script>

例题:鼠标移动到div上变颜色

<style>
#test{
	width: 100px;
	height: 100px;
	background-color: #ccc;
}
</style>
<div id="test"></div>
<script>
window.onload=function(){
	var oDiv=document.getElementById('test');
	//点击尺寸变大
	oDiv.addEventListener('click', function(){
		var oStyle=window.getComputedStyle(oDiv);
		oDiv.style.width=parseInt(oStyle.width)+10+'px';
		oDiv.style.height=parseInt(oStyle.height)+10+'px';
	});
	//鼠标移上去更改颜色
	oDiv.addEventListener('mouseover',function(){
		this.style.backgroundColor='#FF0000';
	})
	//鼠标离开更改颜色
	oDiv.addEventListener('mouseout',function(){
		this.style.backgroundColor='#cccccc';
	})
}
</script>

运行结果

在这里插入图片描述

2、添加同类型事件

注意:DOM1级事件添加多个同类型的事件只有最后一个起作用。所有DOM1级是不支持添加多个同类型事件

DOM2 级可以添加多个同类型事件

<script>
window.onload=function(){
	var oBtn=document.getElementById('btn');
	oBtn.addEventListener('click', function(){
		alert('锄禾日当午');
	});
	oBtn.addEventListener('click',function(){
		alert('汗滴禾下土');
	})
}
</script>
<input type="button" value="点击" id='btn'>

3、取消DOM2级事件

语法:

oBtn.removeEventListener(事件, 函数名);

要取消DOM2级事件必须是有名函数,不可以是匿名函数

例题

<body>
<script>
function fun1(){
	alert('锄禾日当午');
}
function fun2(){
	alert('汗滴禾下土');
}

window.onload=function(){
	var oBtn=document.getElementById('btn');
	oBtn.addEventListener('click',fun1);	//添加事件
	oBtn.addEventListener('click',fun2);	//添加事件

	document.getElementById('btn2').onclick=function(){	//取消DOM2级事件
		oBtn.removeEventListener('click', fun1);
		oBtn.removeEventListener('click',fun2);
	}
}
</script>
<input type="button" value="点击" id='btn'><br>
<input type="button" value="取消事件" id='btn2'>
</body>
1.2.3 事件流

多个嵌套的标记拥有相同事件,一个元素的事件触发,同时会触发其他元素相同的事件,称为事件流

事件流有两种:

1、冒泡型:事件有内往外(false)

2、捕捉型:事件由外往内(true)

在这里插入图片描述

注意:DOM1级不能操作事件流,只能是冒泡型,不能改变

例题:通过DOM2级事件操作事件流

<body>
<style>
#aa{
	width:150px;
	height: 150px;
	background-color: #F00;
}
#bb{
	width:100px;
	height: 100px;
	background-color: #090;
}
#cc{
	width: 50px;
	height: 50px;
	background-color: #00F;
}
</style>
<div id="aa">aa
	<div id="bb">bb
		<div id="cc">cc</div>
	</div>
</div>
<script>
window.onload=function(){
	document.getElementById('aa').addEventListener('click', function(){
		alert('aa')
	}, true);
	
	document.getElementById('bb').addEventListener('click', function(){
		alert('bb')
	}, true);

	document.getElementById('cc').addEventListener('click', function(){
		alert('cc')
	}, true);   //true 表示捕捉型, false表示冒泡型【冒泡】
}
</script>
</body>

运行结果

在这里插入图片描述

常用事件:

onblur:		失去焦点
onfocus:	获得焦点
onload:		当页面加载的时候
onunload:	当页面卸载的时候
onchange:	发生改变的时候
onclick:	单击的时候
onmouseover:	当鼠标移上去
onmouseout:		当鼠标移走
onmousemove:	当鼠标移动
onmousedown:	当鼠标按下去
onmouseup		当鼠标抬起
onsubmit:		当表单提交
onkeydown		当键盘按下去
onkeyup			当键盘抬起

1.3 事件对象

1.3.1 概述

每个事件发生的时候,计算机都会产生相应的对象,用来保存事件发生时候计算机的状态。

1.3.2 获取事件对象

当事件发生的时候,事件对象自动传递给事件处理函数。

//DOM1级获取事件对象
btn.οnclick=function(evt){  //evt表示事件对象
	
}
//DOM2级获取事件对象
btn.addEventListener('click', function(evt){
	
})
1.3.3 事件对象应用

应用一:阻止事件流

<script>
window.onload=function(){
	document.getElementById('aa').addEventListener('click', function(evt){
		alert('aa');
		evt.stopPropagation();	//停止事件流
	}, false);
	
	document.getElementById('bb').addEventListener('click', function(evt){
		alert('bb');
		evt.stopPropagation();	//停止事件流
	}, false);

	document.getElementById('cc').addEventListener('click', function(evt){
		alert('cc');
		evt.stopPropagation();	//停止事件流
	}, false);
}
</script>

//Propagation:传播

提醒:事件对象也可以阻止DOM1级的事件流

<script>
window.onload=function(){
	document.getElementById('aa').onclick=function(evt){
		alert('aa');
		evt.stopPropagation();
	}
	document.getElementById('bb').onclick=function(evt){
		alert('bb');
		evt.stopPropagation();
	}
	document.getElementById('cc').onclick=function(evt){
		alert('cc');
		evt.stopPropagation();
	}
	
}
</script>

小结:可以通过事件对象阻止事件流,不管是DOM1级的还是DOM2级的都可以阻止

应用二:阻止浏览器默认动作

表单提交时候,浏览器会根据action的值进行跳转,这个动作称为浏览器的默认动作。

return false:阻止DOM1级的默认动作

evt.preventDefault():阻止DOM1和DOM2级的默认动作

例题

<body>
<form action="" id='frm'>
	请输入一个数 <input type="text" name='num' id="num"><br>
	<input type="submit" value="提交">
</form>
<script>
window.onload=function(){
	//阻止DOM1级的默认动作
	document.getElementById('frm').onsubmit=function(evt){
		if(isNaN(document.getElementById('num').value)){
			alert('请输入一个数');
			//return false;			//阻止DOM1级的默认动作
			evt.preventDefault();	//阻止DOM1级和DOM2的默认动作
		}
	}

	//阻止DOM2级的默认动作
	/*
	document.getElementById('frm').addEventListener('submit', function(evt){
		if(isNaN(document.getElementById('num').value)){
			alert('请输入一个数');
			evt.preventDefault();	//阻止DOM1级和DOM2的默认动作
		}
	});
	*/
}
</script>

应用三:光标位置

evt.screenX		相对于屏幕的左上角
evt.screenY

evt.clientX		相对于客户端的左上角,不包含滚动条的距离
evt.clientY

evt.pageX		相对于客户端的左上角,包含滚动条的距离
evt.pageY

evt.offsetX		相对于自身的左上角
evt.offsetY

例题:小鸟跟随鼠标

<style>
#bird{
	position: absolute;
}
</style>
<img src="bird.gif" id='bird'>
<script>
window.onload=function(){
	var oImg=document.getElementById('bird');
	window.onmousemove=function(evt){
		oImg.style.left=evt.clientX+'px';    //将鼠标的x位置付给小鸟距左的距离
		oImg.style.top=evt.clientY+'px';	  //将鼠标的y位置付给小鸟距上的距离
	}
}
</script>

运行结果

在这里插入图片描述

1.4 作业

作业一:判断闰年

<script>
window.onload=function(){
	document.getElementById('btn').onclick=function(){
		var year=document.getElementById('year').value;
		if(year==''){
			alert('年份不能为空');	
			document.getElementById('year').focus();	//获取焦点
		}else{
			if(isNaN(year)){
				alert('您输入的不是数字');
				document.getElementById('year').select();	//选中文本框的内容
			}else{
				if(year.indexOf('.')!=-1){
					alert('不能输入小数');
					document.getElementById('year').select();
				}else{
					if(year<1){
						alert('必须输入正整数');
						document.getElementById('year').select();
					}else{
						if(year%4==0 && year%100!=0 || year%400==0){
							alert(year+'是闰年');
						}else{
							alert(year+'是平年');
						}
					}
				}
			}
		}
	}
}
</script>
<form action="">
	请输入年份: <input type="text" id="year">
	<input type="button" id='btn' value="判断闰年">
</form>

作业二:判断成绩

<form action="">
	语文:<input type="text" id="ch"> <br>
	数学:<input type="text" id="math"> <br>
	<input type="button" value="判断成绩" id='btn'>
</form>
<script>
window.onload=function(){
	document.getElementById('btn').onclick=function(){
		var ch=document.querySelector('#ch').value;	//语文成绩
		var math=document.querySelector('#math').value;	//数学成绩
		if(ch=='' || isNaN(ch) || ch<0 ||ch>100){
			alert('语文成绩必须在0-100之间');
			document.getElementById('ch').select();
		}else if(math=='' || isNaN(math) || math<0 || math>100){
			alert('数学成绩必须在0-100之间');
			document.getElementById('math').select();
		}else{
			//ch=parseInt(ch);		//转成整数类型
			//math=parseInt(math);	//转成整数类型
			ch=parseFloat(ch);		//转成浮点型
			math=parseFloat(math);
			var avg=(ch+math)/2;
			alert('您的平均分是:'+avg);
			if(avg>=90)
				alert('A');
			else if(avg>=80)
				alert('B');
			else if(avg>=70)
				alert('C');
			else if(avg>=60)
				alert('D');
			else
				alert('E')
		}
		
	}
}
</script>

作业三:更改颜色

<div id="content">
	离离原上草,一岁一枯荣。<br>
	野火烧不尽,春风吹又生。<br>
	远芳侵古道,晴翠接荒城。<br>
	又送王孙去,萋萋满别情。<br>
</div>
<select id="color">
	<option value="#000000">---请选择颜色---</option>
	<option value="#FF0000">红色</option>
	<option value="#009900">绿色</option>
	<option value="#0000FF">蓝色</option>
</select>
<script>
	window.onload=function(){
		document.getElementById('color').onchange=function(){
			document.getElementById('content').style.color=this.value;
		}
	}
</script>

运行结果

在这里插入图片描述

作业四:打印图形

<style>
	body{
		text-align: center;
		font-size: 20px;
	}
	span{
		width: 28px;
		display:inline-block;
	}
</style>
<script>
	for(var i=1;i<=9;i++){
		n=i<=5?i:(10-i);
		n=(2*n)-1;
		for(var j=1;j<=n;j++){
			document.write('<span>*</span>');
		}
		document.write('<br>');
	}
</script>

运行结果

在这里插入图片描述

作业五:打印图形

<style>
span{
	display: inline-block;
	width: 27px;
	font-size: 20px;
	text-align: center;
}
</style>
<script>
for(var i=0;i<=9;i++){
	for(var j=0;j<=9;j++){
		if(i>=2 && i<=7 && j>=2 && j<=7)
			document.write('<span></span>');
		else
			document.write('<span>*</span>');
	}
	document.write('<br>');
}
</script>

运行结果

在这里插入图片描述

作业六:打字机的效果

<body>
<style>
	div{
		width: 300px;
		height: 100px;
		border: #000 solid 1px;
		margin-bottom: 30px
	}
</style>
<div id='content'></div>
<textarea id="txt" cols="30" rows="5"></textarea><br>
<input type="button" value="打印" id='btn'>
<script>
window.onload=function(){
	document.getElementById('btn').onclick=function(){
		var str=document.getElementById('txt').value;		//获取打印的内容
		if(str=='')	//打印内容为空,就终止
			return;
		var n=0;
		var id=setInterval(function(){
			if(n==str.length){
				document.getElementById('content').innerHTML=str;
				clearInterval(id);	//关闭时钟
			}
			else{
				document.getElementById('content').innerHTML=str.substr(0,n)+'_';
				n++;
			}
		}, 100);	//每隔100毫秒截取一次字符串
	}
}
</script>
</body>

运行结果

在这里插入图片描述

作业七:自选彩票(36选)

<style>
	div{
		width: 50px;
		height: 50px;
		float: left;
		border: #000 solid 1px;
		margin-right: 10px;
		text-align: center;
		line-height: 50px;
	}
</style>
<div class="num"></div>
<div class="num"></div>
<div class="num"></div>
<div class="num"></div>
<div class="num"></div>
<div class="num"></div>
<div class="num"></div>
<input type="button" value="机选" id='btn'>
<script>
window.onload=function(){
	document.getElementById('btn').onclick=function(){
		var oDiv=document.getElementsByClassName('num');
		var array=[];	//保存已经生成的数字
		for(var i=0;i<7;i++){
			while(true){
				var num=Math.floor(Math.random()*36)+1;	//生成随机数
				if(array.indexOf(num)==-1){	//数组中不存在
					oDiv[i].innerHTML=num;	//显示数字
					array.push(num);		//将数字保存到数组中
					break;
				}
				
			}
		}
	}
}
</script>

运行结果

在这里插入图片描述

作业八:本月第一天是星期几

<script>
var array=['天','一','二','三','四','五','六'];
var date=new Date();
date.setDate(1);	//设置本月的第一天
var n=date.getDay();	//返回星期的索引号
console.log('本月第一天星期'+array[n]);
</script>

作业九:倒计时

<div id="t"></div>
<script>
window.onload=function(){
	var date2=new Date(2020,1,1,0,0,0);	//2020年元旦
	var time2=date2.getTime();		//2020年元旦的时间戳
	setInterval(function(){
		var date1=new Date();	//当前时间
		var time1=date1.getTime();	//当前时间戳
		var diff_time=parseInt((time2-time1)/1000);	//距离目标剩余时间(数)
		var day=parseInt(diff_time/3600/24);		//剩余天数
		var hour=parseInt((diff_time/3600)%24);	//剩余小时
		var minute=parseInt((diff_time/60)%60);	//剩余分钟数
		var second=diff_time%60;		//剩余秒数
		document.getElementById('t').innerHTML='距离2020年元旦还有:'+day+'天'+hour+'小时'+minute+'分钟'+second+'秒';
	}, 1000);
}
</script>

运行结果

在这里插入图片描述

作业十:年月日

<select id="year"></select><select id="month"></select><select id="day"></select><script>
//加载年
function initYear(){
	var date=new Date();
	var y=date.getFullYear();
	appendOption('year',y-100,y);
	document.getElementById('year').children[80].setAttribute('selected', 'selected');
}
//加载月
function initMonth(){
	appendOption('month',1,12);
}
//加载日
function initDay(){
	document.getElementById('day').innerHTML='';	//清空日期下的所有子元素
	var n=getDayCount();
	appendOption('day',1,n);
}
/*
*作用:在select元素下添加option
*@param target string 目标id,
*@param start int 起始值
*@param end int 结束值
*/
function appendOption(target,start,end){
	for(var i=start;i<=end;i++){
		var option=document.createElement('option');
		option.innerHTML=i;
		option.setAttribute('value', i);
		document.getElementById(target).appendChild(option);
	}
}
//获取指定月份的天数
function getDayCount(){
	var y=document.getElementById('year').value;
	var m=document.getElementById('month').value;
	if(m==1||m==3||m==5||m==7||m==8||m==10||m==12){
		return 31;
	}else if(m==2){
		if(y%4==0 && y%100!=0 || y%400==0)
			return 29;
		return 28;
	}else{
		return 30;
	}
}
//调用方法
window.onload=function(){
	initYear();
	initMonth();
	initDay();
	document.getElementById('year').onchange=initDay;    //年发生了改变
	document.getElementById('month').onchange=initDay;	  //月发生了改变
}
</script>

运行结果

在这里插入图片描述

作业十一:div尺寸变大

<style>
#test{
	width:100px;
	height: 100px;
	background-color: #ccc;
}
</style>
<div id='test'></div>
<script>
window.onload=function(){
	document.getElementById('test').onclick=function(){
		oStyle=window.getComputedStyle(this);
		var w=oStyle.width;	//获取宽度,带有px
		var h=oStyle.height;
		w=parseInt(w);		//去除px
		h=parseInt(h);		//去除px
		w+=5;
		h+=5;
		document.getElementById('test').style.width=w+'px';//样式都要带有px
		document.getElementById('test').style.height=h+'px';
	}
}
</script>

运行结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值