JavaScript(JS)
一、JavaScript是什么
- 运行在客户端的脚本语言
- 脚本语言:不需要编译,由Js解释器逐行进行解释并执行
- 现在也可基于Node.js技术进行服务器端编译(后台)
二、JavaScript作用
- 表单动态校验(比如:长度不够、不合格,就不用把数据送到数据库后台)
- 网页特效
- 桌面程序(比如:日历–)
- 服务器开发(Node.js)
三、JS(ECMAScript)基础语法
1.js分类
(1).行内式的js直接写到原html代码中
<input type="button" value="未来" onclick="alert('可期')">
(2).内嵌式
<script>
alert('wei');
</script>
(3).外部式
在head中引用
<script src="my.js"></script>
2.注释
(1)单行注释
// ctrl+/
(2)多行注释
/*
*/shift+alt+a
3.输入输出语句
(1)alert(msg):浏览器弹出警示框
<script>
alert('wei');
</script>
(2)console.log(msg):浏览器控制台打印输出信息
<script>
console.log('程序员看的');
</script>
(3)prompt(info):浏览器弹出输入框,用户可以输入
<script>
prompt('你的年龄:');
</script>
4.变量
- 变量是程序在内存中申请的一块用来存放数据的空间
- 使用:1.声明变量 2.赋值
var xiao; xiao = 3; 或者直接声明并赋值(变量的初始化) var xiao = 'xiaojinling'; - 如果声明几个变量,可以只写一个var,并且用逗号隔开
var name='xiao' ,qw=‘123’; - 只声明不赋值,结果是undefined
- 不声明不赋值,报错
- 不声明赋值,其实也可以–
- 变量区分大小写
- 命名遵守驼峰命名法
5.数据类型
- 都用var定义
- 前面加0:八进制,前面加0x:十六进制
- Infinity:无穷大,-Infinity:无穷小
- NaN:非数字 isNaN()可以判断是不是数字
- 字符串转义字符都要用\开头,写到引号里面,最后会实现换行等功能
typeof可以查看变量数据类型 var num=10; console.log(typeof num);
6.arguments使用
1.当我们不确定函数有多少个参数传递时,可用arguments获取,
2.它是一个当前函数的一个内置对象,所有函数都内置了一个arguments对象。
3.arguments对象中存储了传递的所有实参。
4.arguments展示形式是一个伪数组。即:具有length属性、安索引方式存储数据、但是不具有数组的push、pop等方法。
<script>
function cook() {
console.log(arguments);
}
cook(1, 2, 3, 4);
</script>
7.预解析
1.js引擎运行js分为两部分:预解析 与 代码执行 2.预解析js引擎会把js里面所有的var还有funcation提升到当前作用域的最前面 3.代码执行:按照代码书写的顺序从上往下依次执行 4.预解析分为变量预解析(变量提升)和函数预解析(函数提升)
5.变量提升:就是把所有的变量声明提升到当前作用域的最前面,不提升赋值操作
8.创建对象的三种方式
1.利用对象字面量创建对象{}
<script>
var obj={
name: '张三丰',
age: 18,
sayHello: function(){
console.log('hi');
}
}
注意:调用对象属性的两种方法
obj.name
obj['name']
</script>
2.利用new object 创建对象
<script>
var obja = new Object();
obja.name='qwqw';
obj.age=19;
obj.say=function(){
console.log('hi');
}
</script>
3.利用构造函数创建对象 (前面两种创建对象的方式一次只能创建一个对象)
<script>
function Star(uname,age,sex){
this.name=uname;
this.age=age;
this,sex=sex;
}
new Star('liu',18,'nan');
</script>
9.内置对象的一些常用的知识
自己查文档:MDN:https://developer.mozilla.org/zh-CN/
1.随机点名功能实现
<script>
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var arr = ['长', '一', '去', '求'];
console.log(arr[getRandom(0, arr.length - 1)]);
</script>
2.输出日期
<script>
var date = new Date();
console.log(date);
var date1 = new Date('2021-10-11 8:8:8');
console.log(date1);
var date2 = new Date(2021, 10, 1);
console.log(date2);
</script>
3.Date注意:
注意:
- 月份最后要加1!!!!!!!
- 周日返回0!!!!!!!
- 周一返回1!!!!!!
4.日期(时间)格式化
<script>
var date = new Date();
console.log(date.getFullYear());
console.log(date.getMonth());
console.log(date.getDate());
console.log(date.getDay());
console.log(date.getHours());
console.log(date.getMinutes());
console.log(date.getSeconds());
function getTime() {
var time = new Date();
var h = time.getHours();
h = h < 10 ? '0' + h : h;
var m = time.getMinutes();
m = m < 10 ? '0' + m : m;
var s = time.getSeconds();
s = s < 10 ? '0' + s : s;
return h + ':' + m + ':' + s
}
console.log(getTime());
var year = date.getFullYear();
var month = date.getMonth() + 1;
var dates = date.getDate();
var arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
var day = date.getDay();
console.log('今天是' + year + '年' + month + '月' + dates + '日' + arr[day]);
</script>
5.获得Date总的毫秒数,距离1970年1月1日的毫秒数
<script>
var date = new Date();
console.log(date.valueOf());
console.log(date.getTime());
var date1=+new Date();
console.log(date1);
console.log(Date.now());
</script>
6.时间戳转化为年月日时分秒
<script>
function changeTime(timestamp) {
var date = new Date(timestamp * 1000);
Y = date.getFullYear() + '-';
M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds();
return Y + M + D + h + m + s;
}
</script>
7.倒计时制作
用时间戳计算更简单(前后端传时间戳方便) 思路:略
<script>
function countTime(time) {
var nowTime = +new Date();
var inputTime = +new Date(time);
var times = (inputTime - nowTime) / 1000;
var d = parseInt(times / 60 / 60 / 24);
d = d < 10 ? '0' + d : d;
var h = parseInt(times / 60 / 60 % 24);
h = h < 10 ? '0' + h : h;
var m = parseInt(times / 60 % 60);
m = m < 10 ? '0' + m : m;
var s = parseInt(times % 60);
s = s < 10 ? '0' + s : s;
return d + '天' + h + '时' + m + '分' + s + '秒';
}
console.log(countTime('2021-10-1 19:00:00'));
</script>
=============================================================================================================
四、Web Apis阶段–DOM(js页面应用,实现页面交互效果)
1.DOM是什么
文档对象模型(DOM),是W3C组织推荐的处理可拓展标记语言(html或者XML)的标准编程接口。 可以改变网页的内容、结构、样式
2.getElementById获取元素
<body>
<input id="aa" type="button" value="未来" onclick="alert('可期')">
<script>
var a = document.getElementById('aa');
console.log(a);
console.dir(a);
</script>
</body>
3.getElementsByTagId获取元素
<ul id="qw">
<li>12121</li>
<li>12121</li>
<li>12121</li>
<li>12121</li>
</ul>
<script>
var a = document.getElementsByTagName('li');或者qw
console.log(a);
console.dir(a[0]);
</script>
<script>
var a = ul.getElementsByTagName('li');
console.log(a);
console.dir(a[0]);
</script>
4.事件三要素
- 事件是由三部分组成:事件源、事件类型、事件处理程序
- 事件源:时间被触发的对象(按钮)
<button id="xiao">123</button>
<script>
var btn = document.getElementById('xiao');
</script>
- 事件类型:如何触发,比如:鼠标点击(onclick)
- 时间处理程序:通过一个函数完成
btn.onclick = function() {
alert('技能');
}
- 常见的鼠标事件:
5.操作元素----修改元素的内容
1.innerText
<button id="xiao">123</button>
<div>事件</div>
<script>
var btn = document.querySelector('button');
var div = document.querySelector('div');
btn.onclick = function() {
div.innerText = '2021-9-4';
}
</script>
2.innerText与innerHtml区别
innerText不识别标签 innerHtml识别标签 二者除了可以修改元素内容,都可以获得元素里面的内容 获得元素内容innerText不保留空格和换行 innerHtml保留空格和换行
6.操作元素-----改变元素属性
<button id="123">张子枫1</button>
<button id="234">张子枫2</button>
<img src="1.jpg" title="1">
<script>
var btn1 = document.getElementById('123');
var btn2 = document.getElementById('234');
var img = document.querySelector('img');
btn1.onclick = function() {
img.src = '1.jpg';
img.title = '1';
}
btn2.onclick = function() {
img.src = '2.jpg';
img.title = '2';
}
</script>
7.操作元素—密码明文功能实现
html
<div class="login_user">
<input id="name" type="text" placeholder="请输入姓名" value=""><br>
<input id="password" type="password" placeholder="请输入密码" value="">
<label for="">
<img src="img/eyeclose.png" id="eye">
</label>
</div>
js
<script>
var eye = document.getElementById('eye');
var pwd = document.getElementById('password');
var flag = 0;
eye.onclick = function() {
if (flag == 0) {
pwd.type = 'text';
eye.src = 'img/eyeon.png';
flag = 1;
} else {
pwd.type = 'password';
eye.src = pwd.type = 'text';
eye.src = 'img/eyeclose.png';
flag = 0;
}
}
</script>
结果:
8.操作元素—修改元素样式–小广告实现
注意:如果样式修改过多也可以用修改类名的方法实现className。略
<div class="box">
<i class="closebtn">x</i>
<img src="1.jpg">
</div>
<style>
.box {
position: absolute;
top: 1000px;
}
.closebtn {
position: absolute;
top: 6px;
left: 5px;
width: 14px;
border: 1px solid #ccc;
line-height: 14px;
font-family: Arial, Helvetica, sans-serif;
cursor: pointer;
}
</style>
<script>
var btn = document.querySelector('.closebtn');
var box = document.querySelector('.box');
btn.onclick = function() {
box.style.display = 'none';
}
</script>
结果(好喜欢这图~~~~):
9.操作元素—密码框验证信息
<div class="register">
<input type="password" class="ipt">
<p class="message">请输入6~16位密码</p>
</div>
<style>
.message {
display: inline-block;
font-size: 12px;
color: #999;
background: url(img/提示.png) no-repeat left center;
padding-left: 50px;
}
.wrong {
color: red;
background-image: url(img/错误.png)
}
.right {
color: green;
background-image: url(img/对勾.png);
}
</style>
<script>
var ipt = document.querySelector('.ipt');
var mes = document.querySelector('.message');
ipt.onblur = function() {
if (ipt.value.length < 6 || ipt.value.length > 16) {
mes.className = 'message wrong';
mes.innerHTML = '您输入的位数不对,要求6~16位';
} else {
mes.className = 'message right';
mes.innerHTML = '输入正确';
}
}
</script>
结果:
10.操作元素—排他思想(算法)(轮播图小圆圈)
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<script>
var btns = document.getElementsByTagName('button');
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function() {
for (i = 0; i < btns.length; i++) {
btns[i].style.backgroundColor = '';
}
this.style.backgroundColor = 'pink';
}
}
</script>
结果:
11.操作元素–页面换肤效果
<body>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
.huanfu {
overflow: hidden;
margin: 100px auto;
background-color: #fff;
width: 310px;
padding-top: 3px;
}
.huanfu li {
float: left;
margin: 0 1px;
cursor: pointer;
}
.huanfu img {
width: 100px;
}
body {
background: url(img/3.jpg) no-repeat center top;
}
</style>
<ul class="huanfu">
<li><img src="img/1.jpg"></li>
<li><img src="img/2.jpg"></li>
<li><img src="img/3.jpg"></li>
</ul>
<script>
var imgs = document.querySelector('.huanfu').querySelectorAll('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].onclick = function() {
document.body.style.backgroundImage = 'url(' + this.src + ')';
}
}
</script>
</body>
结果:
12.操作元素—表格隔行变色效果
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
table {
width: 800px;
margin: 100px auto;
text-align: center;
border-collapse: collapse;
font-size: 14px;
}
thead tr {
height: 30px;
background-color: skyblue;
}
tbody tr {
height: 30px;
}
tbody td {
border-bottom: 1px solid #d7d7d7;
font-size: 12px;
color: blue;
}
.bg {
background-color: pink;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>代码</th>
<th>名称</th>
<th>最新公布净值</th>
<th>累计净值</th>
<th>前单位净值</th>
<th>净值增长率</th>
</tr>
</thead>
<tbody>
<tr>
<td>003526</td>
<td>农银金穗3个月定期开放债券</td>
<td>1.075</td>
<td>1.079</td>
<td>1.074</td>
<td>+0.047%</td>
</tr>
<tr>
<td>003526</td>
<td>农银金穗3个月定期开放债券</td>
<td>1.075</td>
<td>1.079</td>
<td>1.074</td>
<td>+0.047%</td>
</tr>
<tr>
<td>003526</td>
<td>农银金穗3个月定期开放债券</td>
<td>1.075</td>
<td>1.079</td>
<td>1.074</td>
<td>+0.047%</td>
</tr>
<tr>
<td>003526</td>
<td>农银金穗3个月定期开放债券</td>
<td>1.075</td>
<td>1.079</td>
<td>1.074</td>
<td>+0.047%</td>
</tr>
<tr>
<td>003526</td>
<td>农银金穗3个月定期开放债券</td>
<td>1.075</td>
<td>1.079</td>
<td>1.074</td>
<td>+0.047%</td>
</tr>
<tr>
<td>003526</td>
<td>农银金穗3个月定期开放债券</td>
<td>1.075</td>
<td>1.079</td>
<td>1.074</td>
<td>+0.047%</td>
</tr>
</tbody>
</table>
<script>
var tbody = document.querySelector('tbody').querySelectorAll('tr');
for (var i = 0; i < tbody.length; i++) {
tbody[i].addEventListener('mouseenter', function () {
console.log('onmouseover');
this.style.backgroundColor = 'pink'
})
tbody[i].onmouseout = function () {
console.log('onmouseout');
this.style.backgroundColor = ''
}
}
</script>
</body>
</html>
结果:
13.操作元素–全选
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
padding: 0;
margin: 0;
}
.wrap {
width: 300px;
margin: 100px auto 0;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #c0c0c0;
width: 300px;
}
th,
td {
border: 1px solid #d0d0d0;
color: #404060;
padding: 10px;
}
th {
background-color: #09c;
font: bold 16px "微软雅黑";
color: #fff;
}
td {
font: 14px "微软雅黑";
}
tbody tr {
background-color: #f0f0f0;
}
tbody tr:hover {
cursor: pointer;
background-color: #fafafa;
}
</style>
</head>
<body>
<div class="wrap">
<table>
<thead>
<tr>
<th>
<input type="checkbox" id="j_cbAll" />
</th>
<th>商品</th>
<th>价钱</th>
</tr>
</thead>
<tbody id="j_tb">
<tr>
<td>
<input type="checkbox" />
</td>
<td>iPhone8</td>
<td>8000</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>iPad Pro</td>
<td>5000</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>iPad Air</td>
<td>2000</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Apple Watch</td>
<td>2000</td>
</tr>
</tbody>
</table>
</div>
<script>
var j_cbAll = document.getElementById('j_cbAll');
var j_tbs = document.getElementById('j_tb').getElementsByTagName('input');
j_cbAll.onclick = function () {
for (var i = 0; i < j_tbs.length; i++) {
j_tbs[i].checked = this.checked
}
}
for (var i = 0; i < j_tbs.length; i++) {
j_tbs[i].onclick = function () {
var isAllChecked = true
for (var j = 0; j < j_tbs.length; j++) {
if (j_tbs[j].checked === false) {
isAllChecked = false
break
}
}
j_cbAll.checked = isAllChecked
}
}
</script>
</body>
</html>
结果:
14.操作元素—get.set元素的值,属性
<div id="demo" index="1" class="demodemo">xioa</div>
<script>
var demo = document.getElementById('demo');
console.log(demo.id);
console.log(demo.className);
console.log(demo.getAttribute('id'));
console.log(demo.getAttribute('class'));
console.log(demo.index);
console.log(demo.getAttribute('index'));
demo.setAttribute('index', 'new')
console.log(demo.getAttribute('index'));
demo.className = 'new'
demo.setAttribute('class', 'new')
demo.removeAttribute('class')
console.log(demo.className)
</script>
15.操作元素----tab栏切换效果
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style-type: none;
}
.tab {
width: 978px;
margin: 100px auto;
}
.tab_list {
height: 39px;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
.tab_list li {
float: left;
height: 39px;
line-height: 39px;
padding: 0 20px;
text-align: center;
cursor: pointer;
}
.tab_list .current {
background-color: #c81623;
color: #fff;
}
.item_info {
padding: 20px 0 0 20px;
}
.item {
display: none;
}
</style>
</head>
<body>
<div class="tab">
<div class="tab_list">
<ul>
<li class="current">商品介绍</li>
<li>规格与包装</li>
<li>售后保障</li>
<li>商品评价(50000)</li>
<li>手机社区</li>
</ul>
</div>
<div class="tab_con">
<div class="item" style="display: block;">
商品介绍模块内容
</div>
<div class="item">
规格与包装模块内容
</div>
<div class="item">
售后保障模块内容
</div>
<div class="item">
商品评价(50000)模块内容
</div>
<div class="item">
手机社区模块内容
</div>
</div>
</div>
<script>
var lis = document.querySelectorAll('.tab_list ul li');
var contentItem = document.querySelectorAll('.tab_con .item')
console.log('contentItem: ', contentItem);
for (var i = 0; i < lis.length; i++) {
lis[i].setAttribute('data-index', i)
lis[i].onclick = function () {
for (var j = 0; j < lis.length; j++) {
lis[j].className = ''
}
lis[i].className = 'current'
var index = this.getAttribute('data-index')
for(var k=0;k<contentItem.length;k++) {
contentItem[k].style.display = ''
}
contentItem[index].style.display = 'block'
}
}
</script>
</body>
</html>
结果:
16.操作元素—H5新增的自定义属性
data-开头的为自定义属性
17.节点操作—父节点、子节点
<div>我是div</div>
<span>我是span</span>
<ul>
<li>我是li</li>
<li>我是li</li>
<li>我是li</li>
<li>我是li</li>
</ul>
<div class="demo">
<div class="box">
<span class="erweima">×</span>
</div>
</div>
<script>
var erweima = document.querySelector('.erweima');
console.log(erweima.parentNode);
var ul = document.querySelector('ul')
console.log(ul.childNodes);
console.log(ul.children);
let ol = document.querySelector('ol')
console.log(ol.firstChild);
console.log(ol.lastChild);
console.log(ol.firstElementChild);
console.log(ol.lastElementChild);
console.log(ol.children[0]);
console.log(ol.children[ol.children.length - 1]);
</script>
18.兄弟节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>我是div</div>
<span>我是span</span>
<script>
let div = document.querySelector('div');
let span = document.querySelector('span');
console.log(div.nextSibling);
console.log(span.previousSibling);
console.log(div.nextElementSibling);
console.log(span.previousElementSibling);
function getNextElemntSibling(element){
let el = element
while(el = el.nextSibling){
if(el.nodeType === 1){
return el
}
}
return null
}
</script>
</body>
</html>
19.节点操作—创建添加节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li>123</li>
</ul>
<script>
var ul = document.querySelector('ul');
var li = document.createElement('li')
ul.appendChild(li)
var lili = document.createElement('li')
ul.insertBefore(lili,ul.children[0])
</script>
</body>
</html>
20.节点操作–删除节点
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<button>删除</button>
<ul>
<li>熊大</li>
<li>熊二</li>
<li>光头强</li>
</ul>
<script>
var ul = document.querySelector('ul')
var btn = document.querySelector('button')
btn.onclick = function(){
ul.removeChild(ul.children[0])
if(ul.children.length == 0){
this.disabled = true;
}
}
</script>
</body>
</html>
21.节点操作—复制节点
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
var ul = document.querySelector('ul');
var cloneLi = ul.children[0].cloneNode(true)
ul.appendChild(cloneLi);
</script>
</body>
</html>
22.动态生成表格
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
table {
width: 500px;
margin: 100px auto;
border-collapse: collapse;
text-align: center;
}
td,
th {
border: 1px solid #333;
}
thead tr {
height: 40px;
background-color: #ccc;
}
</style>
</head>
<body>
<table cellspacing="0">
<thead>
<tr>
<th>姓名</th>
<th>科目</th>
<th>成绩</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var datas = [{
name: '魏璎珞',
subject: 'JavaScript',
score: 100
}, {
name: '弘历',
subject: 'JavaScript',
score: 98
}, {
name: '傅恒',
subject: 'JavaScript',
score: 99
}, {
name: '明玉',
subject: 'JavaScript',
score: 88
}, {
name: '大猪蹄子',
subject: 'JavaScript',
score: 60
}];
let tbody = document.querySelector('tbody')
for (let i = 0; i < datas.length; i++) {
let newTr = document.createElement('tr');
tbody.appendChild(newTr);
for(var keys in datas[i]) {
var newTd = document.createElement('td');
newTd.innerHTML = datas[i][keys];
newTr.appendChild(newTd);
}
var editTd = document.createElement('td');
editTd.innerHTML = "<a href='javascript:;'>删除</a>"
newTr.appendChild(editTd)
}
var allA = document.querySelectorAll('tbody tr td a')
for(var i = 0; i < allA.length; i++) {
allA[i].onclick = function(){
tbody.removeChild(this.parentNode.parentNode)
}
}
</script>
</body>
</html>
结果:
23.注册事件(绑定事件)(监听器)(addEventListener)
传统方式只能能添加一个事件 、、、监听器能添加很多
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
*{
box-sizing: border-box;
}
</style>
</head>
<body>
<button>传统注册事件</button>
<button>方法监听注册事件</button>
<button>ie9 attachEvent</button>
<script>
var btns = document.querySelectorAll('button');
btns[0].onclick = function () {
alert('hi');
}
btns[0].onclick = function () {
alert('hao a u');
}
btns[1].addEventListener('click', function () {
alert(22);
})
btns[1].addEventListener('click', function () {
alert(33);
})
btns[2].attachEvent('onclick', function () {
alert(11);
})
</script>
</body>
</html>
24.删除事件(解绑事件)(removeEventListener)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
background-color: teal;
margin: 10px;
}
</style>
</head>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<script>
let divs = document.querySelectorAll('div');
divs[0].onclick = function () {
alert(1);
divs[0].onclick = null;
}
divs[1].addEventListener('click', div1Click)
function div1Click() {
alert(2);
divs[1].removeEventListener('click', div1Click)
}
</script>
</body>
</html>
25.事件对象(event)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
background-color: teal;
}
</style>
</head>
<body>
<div>123</div>
<script>
var div = document.querySelector('div')
div.onclick = function(e) {
e = e || window.event;
console.log(e);
}
</script>
</body>
</html>
26.target 和this区别
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>123</div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
let div = document.querySelector('div');
let ul = document.querySelector('ul');
ul.addEventListener('click', function (e) {
console.log(e.target);
console.log(this);
})
</script>
</body>
</html>
27.跟随鼠标的天使
<!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>Document</title>
<style>
img {
width: 100px;
position: absolute;
}
</style>
</head>
<body>
<img src="img/天使.jpg" alt="">
<script>
var pic = document.querySelector('img');
document.addEventListener('mousemove', function(e) {
var x = e.pageX;
var y = e.pageY;
pic.style.left = x - 50 + 'px';
pic.style.top = y - 50 + 'px';
})
</script>
</body>
</html>
结果:
28.键盘事件
29.按下s键输入内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text">
<script>
let serarch = document.querySelector('input')
document.addEventListener('keyup',function (e){
console.log(e.keyCode);
if(e.keyCode === 83){
serarch.focus();
}
})
</script>
</body>
</html>
五、webapi—BOM
1.BOM
浏览器对象模型,它提供了独立于内容而与浏览器窗口进行交互的对象,其核心对象是window
2.window load窗口加载事件
例如解决以前script只能放在某个div后面,可以把script放在任何地方
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.addEventListener('load', function () {
let btn = document.querySelector('button')
btn.onclick = function () {
console.log(3);
}
console.log(2);
})
document.addEventListener('DOMContentLoaded', function () {
console.log(1);
})
</script>
</head>
<body>
<button>按钮</button>
</body>
</html>
3.调整窗口大小事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 200px;
height: 200px;
background-color: teal;
}
</style>
</head>
<body>
<div>
</div>
<script>
var div = document.querySelector('div')
window.addEventListener('resize', function () {
console.log('变化了');
if (window.innerWidth < 768) {
div.style.backgroundColor = 'pink'
} else {
div.style.backgroundColor = 'teal'
}
})
</script>
</body>
</html>
4.定时器之setTimeout
过了多少秒后打印文字
<!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>Document</title>
</head>
<body>
<script>
setTimeout(function() {
console.log('时间到了');
}, 2000);
function callback() {
console.log('爆炸了');
}
var timer1 = setTimeout(callback, 3000)
var timer2 = setTimeout(callback, 10000)
function callback() {
console.log('爆炸了吗');
}
setTimeout('callback()', 3300)
</script>
</body>
</html>
5.停止定时器clearTimeout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>button</button>
<script>
var btn = document.querySelector('button')
var timer = setTimeout(function () {
console.log('1');
}, 2000)
btn.addEventListener('click', function () {
clearTimeout(timer)
})
</script>
</body>
</html>
6.每隔多长时间调用一次setInterval
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
setInterval(function() {
console.log('1');
}, 1000);
</script>
</body>
</html>
7.倒计时案例
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
div {
margin: 200px;
}
span {
display: inline-block;
width: 40px;
height: 40px;
background-color: #333;
font-size: 20px;
color: #fff;
text-align: center;
line-height: 40px;
}
.ms {
width: fit-content;
padding: 0 5px;
}
</style>
</head>
<body>
<div>
<span class="hour"></span>
<span class="minutes"></span>
<span class="second"></span>
</div>
<script>
var hour = document.querySelector('.hour')
var minutes = document.querySelector('.minutes')
var second = document.querySelector('.second')
var inputTime = +new Date('2021-9-6 09:19:19');
setInterval(countTime, 1000);
function countTime() {
var nowTime = +new Date();
var times = (inputTime - nowTime) / 1000;
var h = parseInt(times / 60 / 60 % 24);
h = h < 10 ? '0' + h : h;
hour.innerHTML = h;
var m = parseInt(times / 60 % 60);
m = m < 10 ? '0' + m : m;
minutes.innerHTML = m;
var s = parseInt(times % 60);
s = s < 10 ? '0' + s : s;
second.innerHTML = s;
}
</script>
</body>
</html>
结果:
8.清除定时器
<button id="start">开始</button>
<button id="stop">停止</button>
<script>
var hours = document.querySelector('.hours')
var minutes = document.querySelector('.minutes')
var seconds = document.querySelector('.seconds')
var ms = document.querySelector('.ms')
var btnStart = document.querySelector('#start')
var btnStop = document.querySelector('#stop')
var timer = null
btnStop.addEventListener('click',function (){
clearInterval(timer)
})
btnStart.addEventListener('click',function (){
clearInterval(timer)
timer = setInterval(fn, 0);
})
</script>
9.发送短信等待几秒案例
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
手机号码: <input type="number"> <button>发送</button>
<script>
let btn = document.querySelector('button')
let timer = null
btn.addEventListener('click', function () {
let initTime = 3
btn.disabled = true
fn()
timer = setInterval(fn, 1000);
function fn() {
if (initTime <= 0) {
clearInterval(timer)
btn.innerHTML = "发送"
btn.disabled = false
} else {
btn.innerHTML = `请在${initTime}后重试!`
initTime--
}
}
})
</script>
</body>
</html>
10.location对象常见属性
// location.href 获取或设置 整个url
// location.host 返回主机(域名)
// location.port 返回端口号 如果未写,返回空字符串
// location.pathname 返回路径
// location.search 返回参数
// location.hash 返回片段 #后面内容
// 测试链接为:https://www.jd.com/?name=andy&age=18#link
// console.log(location.href); // https://www.jd.com/?name=andy&age=18#link
// console.log(location.host); // www.jd.com
// console.log(location.port); //
// console.log(location.pathname); // /
// console.log(location.search); // ?name=andy&age=18
// console.log(location.hash); //#link
11.2秒后跳转页面
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button> 按钮 </button>
<script>
let btn = document.querySelector('button')
btn.addEventListener('click', function () {
setTimeout(function () {
location.href = 'https://www.jd.com'
}, 2000)
})
</script>
</body>
</html>
12.获取url参数
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="index.html" >
用户名: <input type="text" name="username" placeholder="请输入用户名">
<input type="submit" value="提交">
</form>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div></div>
<script>
console.log(location.search);
let search = location.search
let params = search.substr(1)
let result = params.split('=')
let div = document.querySelector('div')
div.innerHTML = "欢迎:"+ result[1]
</script>
</body>
</html>
结果:
13.location一些常见方法
14.history
|