• javascript之dom详细笔记加练习


    Dom的笔记

    根据id获取

    document.getElementById(id)

    	<body>
    		<p id="dom">根据id获取p>
    		<script>
    			var hqu =document.getElementById('dom');
    			console.log(hqu);  //输出结果为:<p id="dom">根据id获取p>
    			console.log(typeof(hqu));  //输出为object
    			console.dir(hqu);  //输出结果为p#dom
    			//console.dir()打印我们返回的元素对象
    	body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    根据标签名获取

    使用document.getElementsByTagName('标签名') 可以返回带有指定标签名的对象的集合,以伪数组的形式存在(如果只有一个li也是伪数组,没有li也是一个空伪数组),伪数组可以遍历可以索引

    		<ul>
    			<li>12各个3li>
    			<li>4 烦烦烦56li>
    		ul>
    		<script>
    			
    			var lis=document.getElementsByTagName('li');
    			console.log(lis[0]);//使用下标输出下标为0的元素
    			for(var i=0;i<lis.length;i++){   //遍历
    				console.log(lis[i]);
    			}
    			
    		script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    <ul>
    			<li>12各个3li>
    			<li>4 烦烦烦56li>
    		ul>
    		<ol>
    			<li>qqqqli>
    			<li>aaaali>
    			
    		ol>
    		<ol>
    			<li>eqeqeqli>
    		ol>
    		<script>
    		//如果想获取OL里面的li,需要先获取OL然后获取li
    		//父元素必须是单个元素(必须指明是哪一个元素对象,获取时不包括父元素)
    		var ol1=document.getElementsByTagName('ol');
    		console.log(ol1[0]);
    		var ol1_li =ol1[0].getElementsByTagName('li');
    		console.log(ol1_li);
    		script>
    			
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    使用document.getElementsByClassName('类名')根据类返回元素对象集合

    <ul>
    	<li class='li1'>12各个3li>
    	<li class='li1'>4 烦烦烦56li>
    ul>
    <script>
    var li_class=document.getElementsByClassName('li1');
    console.log(li_class[0]);
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    使用document.querySelector(选择器(id选择器、类选择器、标签选择器))返回指定选择器的第一个元素

    		<div id='box'>hhhdiv>
    		<ul>
    			<li class='li1'>12各个3li>
    			<li class='li1'>4 烦烦烦56li>
    		ul>
    		<script>
    		var li_class=document.querySelector('.li1');
    		console.log(li_class);
    		var div_id=document.querySelector('#box');
    		console.log(div_id);
    		script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    使用document.querySelectorAll(选择器)返回一个伪数组

    		<ul>
    			<li class='li1'>12各个3li>
    			<li class='li1'>4 烦烦烦56li>
    		ul>
    		<script>
    		var li_class_all=document.querySelectorAll('.li1');
    		console.log(li_class_all);   //一个伪数组
    		console.log(li_class_all[0]);
    	
    		script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    获取body元素获取HTML元素

    <script>
    	//获取body元素
    	var bodyEle=document.body;
    	console.log(bodyEle);
    	console.dir(bodyEle);
    	//获取HTML元素
    	var html1=document.documentElement;
    	console.log(html1);
    	script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    事件基础

    事件有三部分组成,事件源 、事件类型、事件处理程序

    例子:点击一个按钮,弹出提示框
    <button id="but">唐伯虎button>
    	
    	<script>
    	//获取body元素
    	var but1=document.getElementById("but");
    	but1.onclick=function(){
    		alert("秋香");
    	}
    	
    	script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    常见鼠标事件
    鼠标事件触发事件
    onclick鼠标点击左键触发
    onmouseover鼠标经过触发
    onmouseout鼠标离开触发
    onfocus获得鼠标焦点
    onmousemove鼠标移动触发
    onmouseup鼠标弹起触发
    onmousedown鼠标按下触发

    使用element.innerText改变元素内容

    例子:点击按钮出现今天的时间
    <body>
    	<button>更新时间button>
    	<div>显示时间的位置div>
    	<p>11111p>
    	<script>
    		var getdate=function(){
    			var date=new Date();
    			var year=date.getFullYear();
    			var month=date.getMonth();
    			var date1=date.getDate();
    			var hours=date.getHours();
    			var minutes=date.getMinutes();
    			var seconds=date.getSeconds();
    			var xq=date.getDay();
    			var list=['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
    			var xqj=list[xq];
    			return "今天是"+year+"年"+month+"月"+date1+"日"+hours+"时"+minutes+"分"+seconds+"秒"+xqj;
    		}
    		var button=document.querySelector('button');
    		var div1=document.querySelector('div');
    		button.onclick=function(){
    			div1.innerText=getdate();
    		}
    		//不点击按钮,页面一打开自动显示时间
    		var p1=document.querySelector('p');
    		p1.innerText=getdate();
    	script>
    	body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    innerText和innerHTML的区别

    innerText不识别HTML标签,并且删除空格和换行
    innerHTML识别HTML标签,不删除空格和换行
    他俩的共同点是都可以读写
    <body>
    		<div>div>
    	<p>我是
    	  <span>hhhspan>
    	p>
    	<script>
    		var div1=document.querySelector('div');
    		div1.innerText='hhhhh';  //innerText不识别HTML标签
    		div1.innerHTML='啊啊啊啊'; //innerHTML可以识别HTML标签
    		
    		var p1=document.querySelector('p');
    		console.log(p1.innerHTML);   //innerHTML不删除空格和换行
    		console.log(p1.innerText);   //innerText删除空格和换行
    	script>
    	body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    例子:分时显示不同图片不同问候语

    分时显示不同图片和问候语

    <img src="" alt="">
    <div>div>
    
    <script>
    	var date=new Date();
    	var div=document.querySelector('div');
    	var img=document.querySelector('img');
    	console.log(date);
    	var hours=date.getHours();
    	if(hours<12){
    		img.src="./1001.jpg";
    		div.innerHTML='上午好';
    		
    	}
    	else if(hours==12){
    		img.src="./8534071.jpg";
    		div.innerHTML='中午好';
    	}
    	else{
    		img.src="./8537177.jpg";
    		div.innerHTML='下午好';
    	}
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    操作元素之表单元素设置

    <body>
    	<button>按钮button>
    	<input type="text" value="">
    	<script>
    		var button=document.querySelector('button');
    		var text=document.querySelector('input');
    		button.onclick=function(){
    			text.value='hhh';
    			//如果想让某一个表单被禁用,使用disabled,
    			//让button禁止使用
    			button.disabled=true;  //也可以写成 this.disabled=true;
    		}
    	script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    例子:模拟输入密码时,点击眼睛图案看密码,在点击隐藏密码

    <body>
    	<button>按钮button>
    	<input type="password">
    	<script>
    		var button=document.querySelector('button');
    		var input=document.querySelector('input');
    		var flag=0;
    		button.onclick=function(){
    			if(flag==0){
    				input.type="text";
    				flag=1;
    			}
    			else{
    				input.type="password";
    				flag=0;
    			}
    		}
    	script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    我们可以通过JS改变元素的大小、颜色、位置等样式

    注意:1、JS里面的样式采取驼峰命名法,比如说fontSize 、backgroundColor
    2、JS修改style样式操作产生的是行内样式,行内样式权重最高

    		//例子:现在有一个红色盒子,点击盒子让盒子改变颜色和大小style>
    		div{
    			background-color:red;
    			width:200px;
    			height:200px;
    			border:1px solid green;
    		}
    	style>
    		<div>div>
    		
    	<script>
    		var div1=document.querySelector('div');
    		div1.onclick=function(){
    			this.style.backgroundColor='green';
    			this.style.width='300px';
    		}
    		
    	script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    例子:当鼠标有光标时,表单内没有内容,当无光标时表单内有内容

    <body>
    //例子:当鼠标有光标时,表单内没有内容,当无光标时表单内有内容
    	<input type="text" value="请输入内容">
    	<script>
    		var text=document.querySelector('input')
    		text.onfocus=function(){
    			text.value='';
    		}
    		text.onblur=function(){
    			text.value='请输入内容';
    		}
    	script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    element.className当改变多个样式时将样式写入一个类中,也可以把新旧俩个类都赋值给它
    div1.οnclick=function(){ this.className='first second'; }

        <style>
    		.first{
    			border:1px solid red;
    			background-color:red;
    			width:100px;
    			height:100px;
    		}
    		.second{
    			margin-top:300px;
    			background-color:green;
    		}
    	style>
    head>
    <body>
    //例子:当鼠标有光标时,表单内没有内容,当无光标时表单内有内容
    	<div class='first'>div>
    	<script>
    		var div1=document.querySelector('div');
    		div1.onclick=function(){
    			this.className='first second';
    		}
    	script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    例子:判断输入密码长度是否满足要求,不满足要求出现红色提示,满足出现绿色提示

    <style>
    		.red{
    			color:red;
    		}
    		.green{
    			color:green;
    		}
    	style>
    head>
    <body>
    	<input type="password" value=''>
    	<span>span>
    //例子:判断输入密码长度是否满足要求,不满足要求出现红色提示,满足出现绿色提示
    <script>
    	var password=document.querySelector('input');
    	var span=document.querySelector('span');
    	password.onblur=function(){
    		if(password.value.length==5){
    			span.innerHTML='正确';
    			span.className='green';
    		}
    		else{
    			span.innerHTML='错误';
    			span.className='red';
    		}
    	}
    	
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    DOCTYPE html>
    <html lang="zh">
    <head>
    	<meta charset="UTF-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<meta http-equiv="X-UA-Compatible" content="ie=edge">
    	<title>title>
    	<style>
    		.red{color:red}
    		.green{color:green}
    	style>
    head>
    <body>
    	<input class="input1" type="text" value="输入账号/手机号">
    	<input class="input2" type="password" value="输入密码">
    	<button>button>
    	<span>span>
    	<script>
    		var text=document.querySelector('.input1');
    		var password=document.querySelector('.input2')
    		var button=document.querySelector('button');
    		var span=document.querySelector('span');
    		//输入账号模块的光标在和不在的情况
    		text.onfocus=function(){
    			this.value='';
    		}
    		text.onblur=function(){
    			if(value==' '){
    				this.value='输入账号/手机号';
    			}
    			
    		}
    		
    		//输入密码模块的光标在和不在的情况
    		password.onfocus=function(){
    			this.value='';
    		}
    		password.onblur=function(){
    			this.value='输入密码';
    			if(this.value.length==6){
    				span.innerHTML='正确';
    				span.className='green';
    			}
    			else{
    				span.innerHTML='错误';
    				span.className='red';
    			}
    		}
    		
    		//按钮显示密码和隐藏密码
    		var flag=0;
    		button.onclick=function(){
    			if(flag==0){
    				password.type='password';
    				flag=1;
    			}
    			else{
    				password.type='text';
    				flag=0;
    			}
    		}
    		
    		//判断密码长度
    		
    	script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    排他思想

    如果有一组元素,我们想要某一个元素实现某种样式,需要用到循环的排他思想

    1. 所有元素全部清除
    2. 给当前元素设置样式
    3. 注意顺序不能颠倒,首先干掉其他人,在设置自己

    例子:在这里插入图片描述

    <body>
    	<button>按钮1button>
    	<button>按钮1button>
    	<button>按钮1button>
    	<button>按钮1button>
    	
    
    	<script>
    		var button=document.getElementsByTagName('button');
    		//
    		for(var i=0;i<button.length;i++){
    
    			button[i].onclick=function(){
    				for(var j=0;j<button.length;j++){
    					button[j].style.backgroundColor='';
    				}
    				this.style.backgroundColor='red';
    			}	
    		}
    	script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    例子:百度换肤

    <body>
    	<ul class="baidu">
    		<li><img src="./1001.jpg" alt="" width=50px>li>
    		<li><img src="./8534071.jpg" alt="" width=50p>li>
    		<li><img src="./8537177.jpg" alt="" width=50p>li>
    	ul>
    	<script>
    		//获取元素
    		var tp=document.querySelector('.baidu').querySelectorAll('img');
    		//循环事件
    		for(var i=0;i<tp.length;i++){
    			tp[i].onclick=function(){
    				//把this.src给body
    				document.body.style.backgroundImage='url('+this.src+')';
    			}
    		}
    		
    	script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    例子:鼠标经过td表格时,当前行背景颜色变化,当鼠标离开时去掉背景颜色(恢复原样)

    1. 鼠标经过 onmoouseover ,鼠标离开 onmouseout
    2. 鼠标经过td表格时,当前行背景颜色变化,当鼠标离开时去掉背景颜色(恢复原样)
    3. 第一行不变,即thead里面不变

    在这里插入图片描述

    <body>
    	鼠标经过 onmoouseover ,鼠标离开 onmouseout
    	鼠标经过ttd表格时,当前行背景颜色变化,当鼠标离开时去掉背景颜色(恢复原样)
    	第一行不变,即thead里面不变
    	
    	<table border=1 width=300px height=150px cellpadding=0 cellspacing=0 align="center" >
    		<thead>
    			<tr>
    				<th>水果th>
    				<th>文具th>
    				<th>方便面th>
    			tr>
    		thead>
    		<tbody>
    			<tr>
    				<td>苹果td>
    				<td>钢笔td>
    				<td>康师傅td>
    			tr>
    			<tr>
    				<td>香蕉td>
    				<td>橡皮td>
    				<td>白象td>
    			tr>
    			<tr>
    				<td>橘子td>
    				<td>尺子td>
    				<td>大骨汤td>
    			tr>
    		tbody>
    	table>
    	<script>
    	//获取到tbody
    		var bg=document.querySelector('table').querySelector('tbody');
    		console.log(bg); //打印tbody
    		//获取到tbody里面tr的伪数组
    		var hang=bg.getElementsByTagName('tr');
    		console.log(hang[0]);  //打印第一个tr
    		//通过遍历每一个行,找出每一行里面的td进行设置
    		for(var i=0;i<hang.length;i++){
    			var gezi=0;
    			gezi=hang[i].getElementsByTagName('td');
    			//通过遍历行里面的格子,从而设置格子
    			for(var j=0;j<gezi.length;j++){
    				//鼠标经过
    				gezi[j].onmouseover=function(){
    					this.style.backgroundColor='red';
    				}
    				//鼠标离开
    				gezi[j].onmouseout=function(){
    					this.style.backgroundColor='';
    				}
    			}
    		}
    	script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

    例子:全选和单个选的

    ![在这里插入图片描述](https://img-blog.csdnimg.cn/ceb92d7ba89548c1ad7d8aac79b4f156.png#pic_center)
    
    ```html
    DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>title>
    	head>
    	<body>
    		<table border=1 width=200px height=100px align="center" cellpadding=0 cellspacing=0>
    			<thead>
    				<tr>
    					<th id="all_check"><input type="checkbox" id="j_cbAll">全选th>
    					<th>商品th>
    					<th>价格th>
    				tr>
    			thead>
    			<tbody id="j_tb">
    				<tr>
    					<td><input type="checkbox">td>
    					<td>苹果11td>
    					<td>5800td>
    				tr>
    				<tr>
    					<td><input type="checkbox">td>
    					<td>苹果13td>
    					<td>7899td>
    				tr>
    				<tr>
    					<td><input type="checkbox">td>
    					<td>荣耀20td>
    					<td>2899td>
    				tr>
    			tbody>
    		table>
    		<script>
    		    var j_cbAll = document.getElementById('j_cbAll');
    		    var tds = document.getElementById('j_tb').querySelectorAll('input');
    		    j_cbAll.onclick = function () {
    		        for (var i = 0; i < tds.length; i++) {
    		            tds[i].checked = this.checked;
    		        }
    		    }
    		    //2. 下面复选框需要全部选中
    		    for (var i = 0; i < tds.length; i++) {
    		        tds[i].onclick = function () {
    		            var flag = true;
    		            //每次点击都要检查下面的4个按钮是否全被选中
    		            for (var j = 0; j < tds.length; j++) {
    		                if (!tds[j].checked) {
    		                    flag = false;
    		                    break; //退出for循环,这样可以提高执行效率,只要有一个没选中,就可以为false了
    		                }
    		            }
    		            j_cbAll.checked = flag;
    		        }
    		    }
    		script>
    		
    	body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    节点

    一般节点至少拥有nodeType(节点类型)、nodeName(节点名称)和nodeValue()节点值

    元素节点nodeType=1
    属性节点nodeType=2
    文本节点nodeType=3

    父亲节点
    <ul id="ul">
            <li>1li>
            <li>2li>
            <li>3li>
       ul>
       <script>
        var li=document.getElementsByTagName('li');
        console.log(li[0].parentNode);
       script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    儿子节点

    <ul id="ul">
            <li>1li>
            <li>2li>
            <li>3li>
       ul>
       <script>
        var ul1=document.getElementById('ul');
        console.log(ul1.childNodes);
       script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    children获取所有子元素节点(最常用)

    <ul id="ul">
        <li>1li>
        <li>2li>
        <li>3li>
    ul>
    <script>
    var ul1=document.getElementById('ul');
    console.log(ul1.children);
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    输出第一个元素和最后一个元素的最简单方法

     <ul id="ul">
            <li>1li>
            <li>2li>
            <li>3li>
        ul>
        <script>
        var ul1=document.getElementById('ul');
        console.log(ul1.children[0]);
        console.log(ul1.children[ul1.children.length-1]);
        script>
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    实际开发常用ul.children[0]

    兄弟节点

    1. node.nextSibling返回当前元素的下一个节点,找不到返回null,同样包含所有节点
    2. node.previousSibling返回当前元素上一个兄弟元素,同样包含所有节点
    3. ie9以上: node.nextElementSibling返回当前元素的下一个兄弟元素节点
    4. ie9以上 : node.previousElementSibling返回当前元素的上一个兄弟元素节点

    创建节点

    语法:document.createElement()
    //创建节点li
            var li =document.createElement('li');
    
    • 1
    • 2

    添加节点

    1. 语法:node.appendChild(child)
      node:父级
      括号里面填子级
      node.appendChild()方法将一个节点添加到列表末尾,(添加到后面) 例如:ul[0].appendChild(li);
    2. 语法:node.insertBefore(child,指定元素)
      child:子级元素
      指定元素:父级元素(要添加在什么前面)
      例如:
    <ul>
    	<li>123li>
    ul>
    <script>
       //获取元素
    	var ul=document.querySelector('ul');
    	var li_bf=document.createElement('li');
    	//给新创建的节点li添加内容
        li_bf.innerHTML='aaa';
    	//把li_bf添加到ul里面的ul.children[0]前面
    	ul.insertBefore(li_bf,ul.children[0]);
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    留言板案例

    body>
        <button>发布button>
        <textarea name="" id="" cols="30" rows="10">textarea>
        <ul>
        
        ul>
        <script>
            //获取各个元素
            var btn=document.getElementsByTagName('button');
            var tex=document.getElementsByTagName('textarea');
            var ul=document.getElementsByTagName('ul');
            
            //当按钮被按,则执行函数
           btn[0].onclick=function(){
            //创建节点li
            var li =document.createElement('li');
            //把textarea里面的内容赋值给li
            li.innerHTML=tex[0].value;
            //给ul里面添加li
            ul[0].appendChild(li);
            //清空textarea里面的内容
            tex[0].value='';
           }
        script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    删除节点

    语法:node.removeChild(child)
    node:父亲节点
    child:子节点
    node.removeChild()方法从DOM中删除一个子节点,返回删除的节点
    例子:点击按钮删除ul里面的li

    在这里插入图片描述

    <body>
        //例子删除节点
        <button>删除button>
        <ul>
            <li>第一个评论li>
            <li>第二个评论li>
            <li>第三个评论li>
        ul>
        <script>
         //获取button
         var btn=document.querySelector('button');
          //获取ul
          var ul=document.querySelector('ul');
          //当按钮被点击
          btn.onclick=function(){
            if(ul.children.length==0){
                btn.disables=true;
            }
            else{
                ul.removeChild(ul.children[0]);
            }
            
          }  
        script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    例子:留言板的发布与删除
    ![在这里插入图片描述](https://img-blog.csdnimg.cn/7bfe42ff9b3749b484b2bd869c86eb22.png#pic_center)
    <body>
        //留言板的发布与删除
        <textarea name="" id="" cols="30" rows="10">textarea>
        <button>发布button>
        <ul>
            
        ul>
        <script>
            //获取元素
            var textarea=document.querySelector('textarea');
            var btn=document.querySelector('button');
            var ul=document.querySelector('ul');
            //事件源  按钮被点击
            btn.onclick=function(){
                //判断textarea里面是否输入内容
                if(textarea.value==''){
                    alert('您输入的内容为空,请重新输入');
                }
                else{
                    //创建节点
                var li=document.createElement('li');
                    //把textarea里面的内容赋值给li
                    li.innerHTML=textarea.value+"删除";
                    //添加节点
                    ul.appendChild(li);
                    //当发布后让textarea内容为空
                    textarea.value='';
                }
                //获取所有的a标签
                var a=document.querySelectorAll('a');
               // 删除元素 删除的是当前链接的li  它的父亲
                for(var i=0;i<a.length;i++){
                    a[i].onclick=function(){
                        //node.removeChild(child); 删除的是 li 当前a所在的li  this.parentNode;
                        ul.removeChild(this.parentNode);
                    }
                }
            }
        script>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    赋值节点node.cloneNode()

    node.cloneNode()方法返回调用该方法的节点的一个副本
    • 如果括号里面为空或者为false,则是浅拷贝,即只赋值节点,不复制子节点以及内容
    • 如果括号里面为true,则为深拷贝,即复制节点又复制内容
    • 复制完添加后才显示
    • ul>
      <body>
          <ul>
              <li>11li>
          ul>
          <script>
              //先获取要复制的元素
              var li=document.querySelector('li');
              //复制元素
              var li2=li.cloneNode(true);  //如果括号里面是true,则为深拷贝
              var li3=li.cloneNode();   //如果括号里面是空或者false,则为浅拷贝
              //添加元素   复制的元素必须添加后才显示
              li.appendChild(li2);   //添加到li的后面
              li.appendChild(li3);
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16

      例子:动态生成表格

      在这里插入图片描述

      DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Documenttitle>
          <style>
              table{
                  border:1px solid red;
                  width:400px;
                  height: 50px;
                  text-align: center;
                  line-height: 50px;;
              }
              th{
                  border:1px solid red;
                  background-color:rgb(153, 153, 146);
      
              }
              td{
                  border:1px solid red;
              }
          style>
      head>
      <body>
          <table cellspacing="0" cellpadding="0"  align="center">
              <thead>
                  <tr>
                      <th>姓名th>
                      <th>科目th>
                      <th>成绩th>
                      <th>操作th>
                  tr>
              thead>
              <tbody>
      
              tbody>
                 
              <script>
                  //创建一个数组,数组里面包含多个object
                  var lists=[
                      {
                      name:"小红",classname:'math',age:12
                      },
                      {
                      name:"小李",classname:'math',age:11
                      },
                      {
                      name:"小白",classname:'math',age:12
                      }
                  
                  ];
                  //获取tbody
                  var tbody=document.querySelector('tbody');
                  var length =lists.length;   //得出需要几个行
                  for(var i=0;i<length;i++){
                      //创建行
                      var tr =document.createElement('tr');
                      //添加行
                      tbody.appendChild(tr);
                      
                      //通过for循环判断对象里面的元素有几个,则行里面就有几个格
                      for(var k in lists[i]){
                          //创建td
                          var td =document.createElement('td');
                          //将内容添加到单元格中
                          td.innerHTML=lists[i][k];
                          //添加单元格
                          tr.appendChild(td);
      
                      }
                      //创建带有删除的单元格
                      var del_td = document.createElement('td');
                      //在del_td里面添加a标签,a标签里面放删除俩字
                      del_td.innerHTML='删除';
                      //把带有删除字样的单元格添加到行里
                      tr.appendChild(del_td);
      
                  }
                  //获取所有的a标签
                  var as = document.querySelectorAll('a');
                  //通过循环让a标签被点击时删除行
                  for(var i=0;i<as.length;i++){
                      as[i].onclick=function(){
                          //要删除的行标签是a标签的父亲的父亲
                          tbody.removeChild(this.parentNode.parentNode);
                      }
                  }
                  
              script>
          table>
      body>
      html>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      • 63
      • 64
      • 65
      • 66
      • 67
      • 68
      • 69
      • 70
      • 71
      • 72
      • 73
      • 74
      • 75
      • 76
      • 77
      • 78
      • 79
      • 80
      • 81
      • 82
      • 83
      • 84
      • 85
      • 86
      • 87
      • 88
      • 89
      • 90
      • 91
      • 92
      • 93
      • 94

      高级事件

      注册事件:给元素添加事件称为注册事件或绑定事件 (注册事件分为俩种1、传统方式2、方法监听注册事件)

      1、传统方式

      利用on开头的事件,特点是注册事件唯一性(同一个事件只能被设置一个处理函数,多次注册时最后注册的处理函数会覆盖前面注册的事件

      方法监听注册事件

      addEventListener()它是一个方法,特点:同一个元素同一个事件可以注册多个监听器,并且按顺序执行
      该方法接收三个参数eventTarget.addEventLIstener(type,listener[,use(apture)])
    • type:事件类型字符串,如click、mouseover注意这里不带on
    • listener:事件处理函数,事件发生时会调用该监听函数
    • useCapture:可选参数,是一个布尔值,默认是false
    • <body>
          <button>按钮button>
          <script>
              //获取元素
              var btn=document.querySelector('button');
              
              btn.addEventListener('click',function(){
                  alert('被点击了');
              })
              btn.addEventListener('click',function(){
                  alert('第二次被点击了');
              })
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14

      删除事件(解绑事件)

    • 1、传统方式进行删除解绑事件
    • <body>
          <button>按钮button>
          <script>
              //获取元素
              var btn=document.querySelector('button');
              
              btn.onclick=function(){
                  alert('被点击了');
                  btn.onclick=null;//解绑就让他被点击后为空
              }
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
    • 2、事件监听事件解绑
    • <body>
          <button>按钮button>
          <script>
              //获取元素
              var btn=document.querySelector('button');
              
              btn.addEventListener('click',fun);
              function fun(){
                  alert('被点击');
                  btn.removeEventListener('click',fun);
              }
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13

      DOM事件流

      dom事件流分为三个阶段
      1. 捕获阶段
      2. 当前目标阶段
      3. 冒泡阶段
      addEventListener(type,listener[,useCaptrue])当第三个参数为true则表示在事件捕获阶段处理程序,如果为false则表示在冒泡阶段处理数据,默认为false ![在这里插入图片描述](https://img-blog.csdnimg.cn/580ccdd0dea445b6a3e3a9926a8c4fbf.png)

      例子

      DOCTYPE html>
      <html lang="zh">
      <head>
      	<meta charset="UTF-8">
      	<meta name="viewport" content="width=device-width, initial-scale=1.0">
      	<meta http-equiv="X-UA-Compatible" content="ie=edge">
      	<title>title>
      	<style>
      		.father{
      			width:300px;
      			height:300px;
      			border:1px solid red;
      		}
      		.son{
      			width:200px;
      			height:200px;
      			border:1px solid blue;
      		}
      	style>
      head>
      <body>
      	<div class="father">
      		<div class="son">div>
      	div>
      	<script>
      		var father=document.querySelector('.father');
      		var son=document.querySelector('.son');
      		father.addEventListener('click',function(){
      			alert('father');
      		},true)
      		son.addEventListener('click',function(){
      			alert('son');
      		},false)
      	script>
      body>
      html>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36

      结果:儿子在冒泡阶段,父亲在捕获阶段,所以点击儿子,先执行父亲函数,然后执行儿子函数

      事件对象

      eventTarget.οnclick=function(event){}
      
      • 1
      eventTarget.addEventListener('click',function(event){})
      
      • 1

      这个event就是事件对象代表事情的状态,比如鼠标的状态。事件发生后跟事件有关的一系列信息的集合都在event里面

      这个event是个形参,系统帮我们设置为事件对象,不需要传递实参,当我们注册事件时,event对象会被系统自动创建,并且依次传递给事件监听器

      事件对象的常见属性和方法

    • 1、e.target:返回触发事件的对象(谁触发就返回谁)
    • <body>
          <button>
      
          button>
         <script>
          var btn=document.querySelector('button');
          btn.addEventListener('click',function(e){
              
              console.log(e.target);
          })
         script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
    • 2、e.type 返回事件类型 比如:click、mouseover等
    • 在这里插入图片描述

      <body>
          <button>按钮button>
          <script>
              //获取元素
              var btn=document.querySelector('button');
              
              btn.addEventListener('click',fun);
              function fun(e){
                  alert(e.type);
                  
              }
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
    • 3、e.preventDefault()该方法阻止默认事件(默认程序默认行为)执行,例如不让A标签跳转
    • <body>
          //鼠标常用事件 contextmenu没有右菜单   selectstart不能选中
          哈哈,你没有了右键菜单
          <script>
             document.addEventListener('contextmenu',function(e){
              e.preventDefault();
      
             })
             document.addEventListener('selectstart',function(e){
              e.preventDefault();
             })
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
    • 4、e.stopPropagation阻止冒泡
    • 在这里插入图片描述

       <style>
              .father {
                  width:100px;
                  height:30px;
                  border:1px solid red;
              }
              .son{
                  width:50px;
                  height:30px;
                  border:1px solid blue;
              }
          style>
      head>
      <body>
          <div class="father">
              <div class="son">
                 
              div>
          div>
          <script>
          //获得函数
              var father=document.querySelector('.father');
              var son=document.querySelector('.son');t
              //儿子创建事件监听
              son.addEventListener('click',function(e){
                  alert('son');
                  e.stopPropagation(); //阻止冒泡
              })
              //father创建事件监听
              father.addEventListener('click',function(){
                  alert('father');
      
              })
      
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36

      事件委托

      事件委托原理:不是每一个子节点单独设置事件监听器,而是事件监听器<设置在其父节点上,然后利用冒泡排序影响设置的每一个节点/strong>
      例子:当点击li时,触发ul的事件,并且让被点击的li背景颜色为pink

      在这里插入图片描述

      <body>
          <h1>事件委托h1>
          <ul>
              <li>11111li>
              <li>11111li>
              <li>11111li>
              <li>11111li>
          ul>
          <script>
              var ul=document.querySelector('ul');
              ul.addEventListener('click',function(e){
                  alert('11111');
                  e.target.style.backgroundColor='pink';
              })
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16

      鼠标事件

    • 1、contextmenu禁止鼠标右键菜单显示
    • 2、selectstart禁止鼠标选中
    • ```html
      <body>
          //鼠标常用事件 contextmenu没有右菜单   selectstart不能选中
          哈哈,你没有了右键菜单
          <script>
             document.addEventListener('contextmenu',function(e){
              e.preventDefault();
      
             })
             document.addEventListener('selectstart',function(e){
              e.preventDefault();
             })
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      鼠标事件说明
      e.clienX返回相对浏览器窗口可视区的X坐标
      e.clienY返回相对浏览器窗口可视区的Y坐标
      e.pageX返回相对文档页面的X坐标
      e.pageY返回相对文档页面的Y坐标
      e.screenX返回相对电脑屏幕的X坐标
      e.screenY返回相对电脑屏幕的Y坐标

      在这里插入图片描述

      <script>
          document.addEventListener('click',function(e){
              console.log('可视区的X '+e.clientX);
              console.log('可视区的X '+e.clientY);
              console.log('页面文档的X '+e.pageX);
              console.log('页面文档的X '+e.pageY);
              console.log('电脑屏幕的X '+e.screenX);
              console.log('电脑屏幕的X '+e.screenY);
      
          })
         script>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11

      小例子:图片跟着鼠标移动,使用鼠标移动事件mousemove

      在页面中移动,给document注册事件,图片要移动距离,而且不占位置,我们使用绝对定位即可
      t 核心原理:每次移动鼠标,我们都获得最新的鼠标坐标,把这个XY坐标作为图片的top和left值就可以移动图片 ![在这里插入图片描述](https://img-blog.csdnimg.cn/fbe3aed0ce7542498d8bfdc9e79ca854.png#pic_center)
          <style>
              img{
                  width:150px;
                  height:150px;
                  position:absolute;
              }
          style>
      head>
      <body>
          <h1>图片跟着鼠标移动h1>
          <img src="./1001.jpg" alt="">
          <script>
              //获取img元素
              var img=document.querySelector('img');
              document.addEventListener('mousemove',function(e){
                  console.log(e.pageX);
                  console.log(e.pageY);
                  img.style.left = e.pageX + 'px';
                  img.style.top = e.pageY + 'px';
      
              })
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23

      常用键盘事件

      键盘事件触发条件
      onkeyup某个键盘按键被松开时触发(按键弹起时)
      onkeydown某个键盘键被按下时触发
      onkeypress某个键盘键被按下时触发,但是它不识别功能键比如 ctrl 、shift、箭头等
      注意onkeyup、onkeydown、onkeypress有执行顺序和书写位置无关,keydown-keypress-keyup

      键盘事件

          <script>
               //onkeyup  按下某个键盘键被松开时候触发
              document.onkeyup=function(){
                  console.log('我弹起了');
              }
              //onkeydown 按下某个键盘键开时候触发   如果一直按着不放就会一直触发
              //使用事件监听时去掉on
              document.addEventListener('keydown',function(){
                  console.log('我按下了');
              })
              //onkeypress 按下某个键盘键开时候触发,但是它不识别ctrl、shift、箭头键等,如果一直按着不放就会一直触发
              //使用事件监听时去掉on
              document.addEventListener('keypress',function(){
                  console.log('我按下,我不识别ctrl、shift');
              })
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17

      keyCode判断按下哪一个键

    • 1、键盘事件对象中的keyCode属性可以得到相应键的ASCII码值
    • 2、我们的keyup和keydown事件不区分字母大小写,a和A都是65
    • 3、我们的keypress事件区分大小写,a是97 A是65
    • keyCode小练习按下s键,就把光标定在输入框中

      注意:keydown和keypress按下就触发,所以用keyup
      <body>
          <h1>keyCode小练习:按下S键时光标出现在文本框中h1>
          <input type="text">
          <script>
              var inp = document.querySelector('input');
              //keydown和keypress一按就触发,会把s输入到文本框里,所以这里用keyup,当他弹起类,让它获得光标
              document.addEventListener('keyup', function (e) {
                  if (e.keyCode == 83) {
                      inp.focus();
      
                  }
              })
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14

      在这里插入图片描述

      小案例:模仿京东快递输入单号

      案例分析:
    • 1、快递单行输入内容时,上面的大号字体盒子显示输入框里面的内容
    • 2、用innerHTML把快递单号里面的value赋值给大号盒子
    • 3、如果快递单号为空,则把大盒子隐藏
    • 4、keydown和keypress在文本框里面的特点:他们俩个按下就触发了,文字还没有落入文本框,所以执行时文本框里面内容为空
    • 5、keyup触发时,文字已经落入
    • 6、display:none隐藏 display:block显示
    • <body>
          
          <div>
              <div id="qw">div>
              <input type="text">
          div>
          <script>
              //获取元素
              var yc=document.getElementById('qw');
              var inp =document.querySelector('input');
              //当input表单里面有键盘键弹起触发条件
              inp.addEventListener('keyup',function(){
                  //判断,如果input里面有内容,让div显示并且写入input里面的内容
                  //如果input 里面没有内容,则让div隐藏
                  if(this.value==''){
                      yc.style.display='none';
      
                  }
                  else{
                      yc.style.display='block';
                      yc.innerHTML=this.value;
                  }
              })
              //当我们获得焦点时让div显示,当失去焦点时让div隐藏
              inp.addEventListener('focus',function(){
                  if(this.value!=''){
                      yc.style.display='block';
                  }
              })
              inp.addEventListener('blur',function(){
                  yc.style.display='none';
              })
          script>
      body>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
  • 相关阅读:
    十大排序算法C++实现
    源码分析:Actor模型架构
    服务器内存总量和内存条有差异是什么问题 103.239.244.X
    编译OpenWrt内核驱动
    关于 Spring Boot 自动装配你知道多少?
    【web-攻击本地编译性应用程序】(11.3)格式化字符串漏洞
    图论| 827. 最大人工岛 127. 单词接龙
    Pegasus智能家居套件样例开发--软定时器
    2022前端学习笔记
    深入理解 JVM 之——动手编译 JDK
  • 原文地址:https://blog.csdn.net/weixin_49213878/article/details/126738311