JS学习笔记
JavaScript
1.什么是Javascript
Javascript是世界上最流行的脚本语言
Javascript标准:ECMAScript
大部分浏览器支持到es5版本
2.快速入门
2.1引入Javascript
-
内部标签
<!--script标签内写JavaScript代码--> <script> alert("Hello World"); </script>
-
外部引入
<!--外部引入--> <script src="js/MFJS.js"></script>
2.2基本语法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> // 1.定义变量 变量类型 变量名 = 变量值; var num = 1; var name = "Wang"; alert(name); // 2.条件控制 var score=80; if(score>=60 && score<70){ alert("60~70"); } else if(score>=70){ alert(">70") } else { alert("?"); } console.log(score); /* console.log()浏览器控制台输出 */ </script> </head> <body> </body> </html>
2.3数据类型
数值,文本,图形,音频,视视频...
1.数值
js不区分小数和整数,number
123 //整数 12.1 //小数 1.123e3 //科学计数法 -1 //负数 NaN //非数字 Infinity //无限大
2.字符串
'abc' "abc"
3.布尔值
true false
4.逻辑运算
&& //和 || //或 !//非
5.比较运算符
= //赋值 == //等于(类型不一样值一样返回true) === //绝对等于(类型不一样值一样返回false)
- NaN===NaN返回false,NaN与所有数字都不想等,包括自己
- 只能通过isNaN()来判断这个值是否为NaN
浮点是问题:
console.log(1/3===(1-2/3))//false
利用浮点数进行运算,存在精度丢失问题!
math.abs((1/3-(1-2/3)<0.0000001)
6.null和undefined
- null 空
- undefined 未定义
7.数组
JS中数组中未必未为同一类型
// 尽量使用[]保证代码可读性 var arr = [1,2,1.1,true,null,"Hello"]; new Array(1,1,1.1,"hello");
取数组下标越界报错 undefined
8.对象
对象使用大括号,对象的每个属性使用逗号隔开
var person{ name:"xiaowang", age:20, tags:["JS","Web","frontend"] }
取对象的值
person.name "xiaowang"
2.4严格检查模式
<script> 'use strict';//使用严格检查模式,必须写在JS第一行 //ide必须支持es6,才能使用 // 全局变量 var i=1; // 局部变量建议使用let定义 let k=0; </script>
3.数据类型
### 3.1字符串
-
正常字符串使用单引号或双引号包裹
-
转义字符: \
\' \n \t \u4e2d // \u#### unicode字符 \x41 //ASCII
-
多行字符串: ``
var msg = `hello mother fucker`;
-
模板字符串: ${}
let name = "LaoWang"; let chat = `hello ${name}`; // 多行字符串包裹 console.log(chat);
-
字符串长度
str.length
-
字符串的不可变性
-
大小写转换
name.toUpperCase(); name.toLowerCase();
-
字符串索引
name.indexOf('i')//索引字符i的位置
-
字符串字串
name.substring(1) //[char1,charEnd] name.substring(1,3) //[char1,char3),not include char3
3.2数组
Array可以包含任意数据类型
var arr = [1,2,3,4,5];
arr[0]=2;//下标赋值
-
长度
arr.length
给arr.length赋值,数组大小会发生变化,赋值过小会出现元素丢失
-
元素索引
arr.indexOf(2) //获得元素2的下标
一个数组数字字符和数字的索引结果不同
-
截取数组的一部分,返回一个新数组 slice(),类似于substring
let arr = [1,2,3,4,5]; let sliced = arr.slice(1,3);
-
删除元素 delete
delete arr[0] //使用 delete 会在数组留下未定义的空洞
-
拼接数组splice
arr = [1,2,3]; (3) [1, 2, 3] arr.splice(0,1,4,5); //第一个参数0表示拼接元素的位置,第二个参数1表示删除元素的个数(头部开始),其余参数表示定义添加的新元素,执行过程为先删除后拼接。 [1] arr (4) [4, 5, 2, 3]
-
push, pop
arr.push(6,7); //push:插入尾部 console.log(arr); arr.pop();//pop:删除尾部元素 console.log(arr);
-
shift, unshift
arr.unshift(0,1); //unshift头部插入新元素 console.log(arr); arr.shift(); //方法会删除首个数组元素,并把所有其他元素“位移”到更低的索引,返回被“位移出”的字符串 console.log(arr);
-
排序sort
arr=['b','c','a']; (3) ["b", "c", "a"] arr.sort(); (3) ["a", "b", "c"]
-
元素翻转reverse
arr=['b','c','a']; (3) ["b", "c", "a"] arr.reverse(); (3) ["a", "c", "b"]
-
元素拼接contact
arr=['b','c','a']; (3) ["b", "c", "a"] arr.concat('f','e'); //拼接元素返回一个新的数组,对原数组没有影响 (5) ["b", "c", "a", "f", "e"]
-
连接符join
arr (3) ["b", "c", "a"] arr.join('|'); //使用特定的连接符打印数组 "b|c|a"
-
多维数组
arr = [[1,2,3],[4,5,6],['7','8','9']] (3) [Array(3), Array(3), Array(3)] arr[1][2] 6
3.3对象
-
定义对象
'use strict' // var className = { // attribute1Name : value, // attribute2Name : value, // attribute3Name : value // } let person={ name : "li", age : 18, phoneNumber : "110" }
-
对象赋值
person.name = "Liu"; "Liu" person.name; "Liu"
-
动态删减属性delete
delete person.age true person {name: "Liu", phoneNumber: "110"}
-
动态添加,定义新属性并赋值
person.weight = "60KG" "60KG" person {name: "Liu", phoneNumber: "110", weight: "60KG"}
-
判断属性值是否在这个对象中 ’attribute‘ in object
person {name: "Liu", phoneNumber: "110", weight: "60KG"} 'name' in person true // 继承 'toString' in person true
-
判断一个属性是否是这个对象自身拥有的 hasOwnProperty
person.hasOwnProperty('weight') true person.hasOwnProperty('toString') false
3.4流程控制
-
if
'use strict' let age = 10; if(age>3){ alert("haha"); else{ alert("wawa"); } }
-
while
while (weight<100){ weight++; } console.log(weight);
-
for
for (let i = 0; i < 10; i++) { console.log(i); }
-
forEach 循环 es5.1特性
arr.forEach(function(value,index,array){}
该语句需要一个回调函数,作为参数。回调函数的形参,依次为,value:遍历的数组内容;index:对应的数组索引,array:数组本身
let arr = [1,3,4,45,5]; arr.forEach(function (value){ console.log(value) })
-
for In 循环
// for(var arrayIndex in array){} let arr = [1,3,4,45,5]; for (let arrKey in arr) { console.log(arrKey); }
3.5 Map Set
es6
Map:Map
是一组键值对的结构,具有极快的查找速度
初始化Map
需要一个二维数组,或者直接初始化一个空Map
let map = new Map([['li',90],['wang',80],['zhao',85]]);// 二维数组初始化Map
map.set('ye',96); // 设置新的key-value
console.log(map.get('ye'));// get获取value
map.has('li')//判断时候含有key ‘li’
true
map
Map(4) {"li" => 90, "wang" => 80, "zhao" => 85, "ye" => 96}
map.delete('wang') //删除key
true
map
Map(3) {"li" => 90, "zhao" => 85, "ye" => 96}
Set:Set
和Map
类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在Set
中,没有重复的key。
要创建一个Set
,需要提供一个Array
作为输入,或者直接创建一个空Set
:
//无序不重复集合Set
let set = new Set([1,1,2,3,3,5]);
console.log(set);
Set(4) {1, 2, 3, 5}//去重复key
set.add('1');// add添加key
Set(5) {1, 2, 3, 5, "1"}// 一个数字key的本身和它的字符形式的key不同
set.delete('1');//delete删除key
true
set.has(1)//判断1是否在key值表中
true
3.6 iterator迭代器
es6
'use strict'
let arr = [1,2,3,6];
//for-of 遍历数组array
for(let element of arr){
console.log(element);
}
//for-of遍历字典map
let map = new Map([["li",100],["wang",98],["cheng",99]]);
for(let mapValue of map){
console.log(mapValue);
}
//for-of遍历集合set
let set = new Set([1,8,2,5]);
for(let setElement of set){
console.log(setElement);
}
4.函数以及面向对象
4.1 定义函数
定义方式1:
//绝对值函数
function abs(x){
if(x>=0)
return x;
else
return -x;
}
//return后函数结束,返回结果
//没有执行return,函数返回undefined
定义方式2
let abs1 = function (x){
if(x>=0)
return x;
else
return -x;
}
function(x){...}这是一个匿名函数,可以将结果幅值给abs,并通过abs调用函数
调用函数
abs(10)//10
abs(-10)//10
参数问题:JS函数可以传递任意参数,如何保证函数传递的参数是正确的?
function abs(x){
//typeof判断传入参数类时候是数字
if(typeof x != 'number')
//非数字时抛出异常throw
throw 'Not a number';
if(x>=0)
return x;
else
return -x;
}
arguments
arguments代表所有传入参数的数组
let abs1 = function (x){
for (let i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
if(x>=0)
return x;
else
return -x;
}
>abs1(-10,10,2,3,4,12)
-10
10
2
3
4
12
10//abs1(-10)
rest
es6
获取除了已经定义的参数外的所有参数
'use strict';
function testRest(a,b,...rest){
//任意长度的加法
for (let i = 0; i < arguments.length; i++) {
if(typeof arguments[i] != 'number') //输入非数字时抛出错误
throw 'Not a number';
}
let sum;
if(arguments.length <2){ //参数小于2时抛出错误
throw 'Lack Parameters';
}
else {
sum = a+b;
for (let i = 0; i < rest.length; i++) {
sum += rest[i]; // 加上剩余参数
}
}
return sum;
}
4.2 变量作用域
JS中,var变量实际时有作用域
-
函数体中声明的变量,函数体外不可调用。
-
在函数嵌套时,内部函数可以调用外部函数的成员,外部函数不可以调用内部函数的成员
-
内部函数变量与外部函数变量重名,内部函数屏蔽外部函数的变量
-
js执行引擎会将后声明的变量提起,但不会将赋值提前
全局函数
'use strict';
//全局变量
var x = 1;
function put(){
console.log(x)
}
put();
全局对象window
put();
var x = 'sss';
alert(x);
alert(window.x); //默认所有全局变量绑定在window对象下
alert()
也绑定在window
下
JS中只有一个全局作用域,任何变量或函数,未在其自身的作用域内找到,就会向外查找,如果全局作用域为找到,报错RefrenceError
规范
如果所有全局变量都定义在全局作用域上时,对于不同的js文件会造成冲突。
解决:将自定全局变量放入唯一名字的空间中
//解决全局变量冲突
var MyVars = {};
MyVars.name = "myVars";
MyVars.add = function (a,b){
return a+b;
}
console.log(MyVars.name);
console.log(MyVars.add(1,3));
局部作用域let (es6)
for(let i=0;i<10;i++){
console.log(i);//输出0-9
}
console.log(i);//无输出
常量const (es6)
const PI = '3.1416'
console.log(PI);
PI = '1'; //ERROR!
常量不能修改
4.3 方法
定义方法
//完整定义
let Self = {
name : "hu",
birthYear: '2000', //属性
getAge : function (){ //方法
let thisYear = new Date().getFullYear();
return thisYear - this.birthYear;
}
}
console.log(Self.getAge());
//分开定义
let Self = {
name : "hu",
birthYear: '2000',
age: getAge
}
function getAge(){
let thisYear = new Date().getFullYear();
return thisYear - this.birthYear; //调用类的birthYear
}
console.log(Self.age());//21
console.log(getAge());//NaN,全局对象window中无this中无birthYear
apply 控制this指向
指定函数的this
指向哪个对象,可以用函数本身的apply
方法,它接收两个参数,第一个参数就是需要绑定的this
变量,第二个参数是Array
,表示函数本身的参数。
functionName.apply(className,[paraArray])
let Self = {
name : "hu",
birthYear: '2000',
age: getAge
}
function getAge(){
let thisYear = new Date().getFullYear();
return thisYear - this.birthYear;
}
console.log(Self.age());//21
console.log(getAge());//NaN
console.log(getAge.apply(Self,[]));//21
5. 内部对象
标准对象
typeof 1234
"number"
typeof "ss"
"string"
typeof true
"boolean"
typeof NaN
"number"
typeof []
"object"
typeof {}
"object"
typeof Math.sin
"function"
typeof undefined
"undefined"
5.1 Date
let now = new Date(); //Sat Apr 03 2021 20:10:22 GMT+0800 (中国标准时间)
now.getFullYear();//
now.getMonth();//
now.getDay();// 星期几
now.getDate();// 日
now.getHours();//
now.getMinutes();//
now.getSeconds();//
now.getTime();// 时间戳 全世界统一 milliseconds(ms) From 1970 1.1 0:00:00 to now
console.log(new Date(1617451822975)) //时间戳转时间
时间格式转换
date = new Date(1617451985385)
Sat Apr 03 2021 20:13:05 GMT+0800 (中国标准时间)
// 默认时间
date.toTimeString()
"20:13:05 GMT+0800 (中国标准时间)"
//默认日期
date.toDateString()
"Sat Apr 03 2021"
// GMT ISO UTC 时间
date.toGMTString()
"Sat, 03 Apr 2021 12:13:05 GMT"
date.toISOString()
"2021-04-03T12:13:05.385Z"
date.toUTCString()
"Sat, 03 Apr 2021 12:13:05 GMT"
//本地 日期时间
date.toLocaleString()
"2021/4/3下午8:13:05"
date.toLocaleTimeString()
"下午8:13:05"
date.toLocaleDateString()
"2021/4/3"
5.2 JSON
什么是JSON
JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。
JS中一切皆为对象,任何JS支持的类型都可用JSON表示;
格式:
- 对象{}
- 数组[]
- 所有键值对,都用key:value表示
JS对象和JSON转换
let user = {
userName:"Dean",
age: 21,
sex : "Male"
};
//对象转化为JSON
let userJSON = JSON.stringify(user);
"{"userName":"Dean","age":21,"sex":"Male"}"//JSON
//JSON转对象
let userOBJ = JSON.parse(userJSON);
{userName: "Dean", age: 21, sex: "Male"}//OBJ
5.3 Ajax
- 原生JS写法 xhr异步请求
- jQuery封装好的方法 $("#name").ajax("")
- axios 请求
6.面向对象编程
6.1 什么是面向对象
- 类:模板
- 对象:类的实例
构造函数创建对象
//构造函数创建对象
function Student_1(id,name){
this.name = name;
this.id = id;
this.selfIntroduction = function (){
alert("I am "+this.name+"id "+this.id)
}
}
//关键字new来调用这个函数,并返回一个对象,如果不写new,这就是一个普通函数,它返回undefined
let XiaoLi = new Student_1('002','XiaoLi');
XiaoLi.selfIntroduction();
_proto_ 继承
//proto继承
let Student = {
id : '000',
name : "",
read: function (){
console.log(this.name+" is reading");}
};
let XiaoMing = {
id: '001',
name: 'XiaoMing'
};
// 小明的原型是Student
XiaoMing.__proto__ = Student;
// 继承了Student的read方法
XiaoMing.read();
class 继承 (es6)
-
定义一个类,属性,方法
//定义一个学生类 class Student{ // 构造器传入参数 constructor(id,name) { this.id = id; this.name = name; } // 定义方法 read(){ alert(this.name+" is reading") } } let XiaoWang = new Student('001','XiaoWang'); let XiaoHong = new Student('002','XiaoHong'); XiaoHong.read();
-
继承(本质上是原型继承)
// 继承 class PrimaryStudent extends Student{ constructor(id,name,grade) { super(id,name);//继承id和name属性 this.grade = grade; } read() { //重写read()方法 alert(this.grade + " grade student "+this.name +" is reading"); } } let XiaoWang = new PrimaryStudent('002','XiaoWang',5); XiaoWang.read();
原型链
每个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。当原型对象等于另一个类型的实例,此时的原型对象将包含一个指向另一个原型的指针,相应地,另一个原型中也包含着一个指向另一个构造函数的指针。假如另一个原型又是另一个类型的实例,那么上述关系依然成立。如此层层递进,就构成了实例与原型的链条。这就是所谓的原型链的基本概念。
7. 操作BOM对象*
浏览器
Javascript和浏览器的关系
JS的诞生就是为了在浏览器中运行
BOM:浏览器对象模型
- IE
- Chrome
- Safari
- FireFox
window
window 代表浏览器窗口
window.alert("Fuck")
undefined
window.innerHeight
217
window.innerWidth
624
window.outerHeight
936
window.outerWidth
597
Navigator
Navigator封装了浏览器信息
navigator.appName
"Netscape"
navigator.appCodeName
"Mozilla"
navigator.userAgent
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0"
navigator.platform
"Win32"
navigator.appVersion
"5.0 (Windows)"
navigator
可被人为修改
screen
screen.width
1920
screen.height //尺寸
1080
location*
host: "offlintab.firefoxchina.cn"
href: "http://offlintab.firefoxchina.cn/"
protocol: "http:"
reload: function reload()//刷新网页
location.assign('https://www.baidu.com')//设置新地址
document
document代表当前页面,HTML DOM文档树
document.title
"Title"
document.title = 'Test'
"Test"
获取文档数节点
<dl id="dl">
<dt>term1</dt>
<dd>1</dd>
<dd>3</dd>
<dt>term2</dt>
<dd>2</dd>
<dd>4</dd>
</dl>
<script>
let elem = document.getElementById('dl');
console.log(elem);
</script>
获取cookie
document.cookie
"0kLe_2132_lastvisit=1617460096; 0kLe_2132_sid=gV7bK7; 0kLe_2132_lastact=1617463697%09home.php%09misc; 0kLe_2132_sendmail=1; Hm_lvt_d78cc3d5d410149533738ffc6006a9c6=1617463697; Hm_lpvt_d78cc3d5d410149533738ffc6006a9c6=1617463697"
history
history.back()//后退
history.forward()//前进
8.操作DOM对象*
DOM:文档对象模型
核心
浏览器就是一个DOM树形结构
-
更新DOM节点
-
遍历DOM节点
-
删除DOM节点
-
添加DOM节点
获得DOM节点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="father">
<h1>标题1</h1>
<p class="p1">P1</p>
<p id="p2">P2</p>
</div>
<script>
let h1 = document.getElementsByTagName('h1');
let p1 = document.getElementsByClassName('p1')
let p2 = document.getElementById('p2');
let father = document.getElementById('father');
let children = father.children;//获取子节点
let firstChild = father.firstChild;//获取第一个子节点
let lastChild = father.lastChild;//获取最后一个子节点
</script>
</body>
</html>
更新节点
- 操作文本
id1.innerText = '223' // 修改文字
id1.innerHTML = '<strong>123</strong>' //修改html
- 操作样式
id.style.color = 'yello'
id.style.fontsize = '20px'
id.style.padding = '2em'
删除节点
步骤:先找到父节点再删除
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="id1">
<p id = 'p1'>shs1</p>
<p>sh2s</p>
<p>shs3</p>
</div>
<script>
let p1 = document.getElementById('p1'); //获得需要删除的节点
let father = id1.parentElement; // 获得父节点
father.removeChild('p1'); //删除需删除的节点
// 删除节点是一个动态的过程
father.removeChild(father.children[0]); //删除第0个子节点后,原来的第一个子节点编程现在的第0个子节点
father.removeChild(father.children[1]); // 删除了原本的第二个节点
father.removeChild(father.children[2]); // 报错,此时没有第二个节点
</script>
</body>
</html>
插入节点
-
某个节点直接使用操作文本的方法修改节点会将节点中的内容全部覆盖
-
追加节点
append
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p id="JavaWeb">JavaWeb</p> <div id = 'list'> <p>HTML</p> <p>CSS</p> <p>JavaScript</p> </div> <script> let list = document.getElementById('list'), JavaWeb = document.getElementById('JavaWeb'); list.appendChild(JavaWeb); //list节点插入子节点JavaWeb </script> </body> </html>
-
创建节点插入
createElement
let nodejs = document.createElement('p'); // 创建p标签 nodejs.id = 'nodejs'; // 创建p标签id nodejs.innerText = "nodejs"; // 创建标签内容 list.appendChild(nodejs); //最追加到list的子节点 let body = document.getElementsByTagName('body')[0]; //获取标签 body.setAttribute('style','background:green');// 设置标签属性
-
insertBefore
let jQuery = document.createElement('p'); jQuery.innerText='jQuery'; //新节点 list.insertBefore(jQuery,list.children[0]); //node.insertBefore(newNode,node.children[n])
9.操作表单(验证)
表单:form DOM树
- 文本框 text
- 下拉框 select
- 单选框 checkbox
- 多选框 radio
- 隐藏域 hidden
- 密码框 password
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="post">
<p>
<span>user name: </span><input type="text" id="userName">
</p>
<p>
<span>sex : </span>
<input type="radio" name="sex" value="male" id="sex_male">male
<input type="radio" name="sex" value="female" id="sex_female">female
<input type="radio" name="sex" value="transgender"id="sex_cross">trans
</p>
</form>
<script>
let username = document.getElementById('userName'),
sexMale = document.getElementById('sex_male'),
sexFemale = document.getElementById('sex_female'),
sexTrans = document.getElementById('sex_cross');
username.value = '111'; //修改输入框的值
sexMale.checked = true; //修改复选框选中
</script>
</body>
</html>
提交表单
- 隐藏密码方法1:提交时md5加密赋值password
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="md5.js"></script>
</head>
<body>
<form action="#" method="post">
<p>
<span>username: </span><input type="text" id="username" name="username">
</p>
<p>
<span>password: </span><input type="password"id="password" name="password">
</p>
<!-- 绑定事件onclick被点击 -->
<button type="submit" onclick="sub()">submit</button>
</form>
<script>
function sub(){
let username = document.getElementById('username'); //
let pwd = document.getElementById('password'); //
pwd.value =calcMD5(pwd.value);
}
</script>
</body>
</html>
- 隐藏域提交password
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="md5.js"></script>
</head>
<body>
<!--表单绑定提交事件
return sub() 提交函数返回true提交
false 提交失败
-->
<form action="#" method="post" onsubmit="return sub()">
<p><span>username: </span><input type="text" id="username" name="username"></p>
<p><span>password: </span><input type="password" id="input-password"></p>
<!-- 隐藏域提交密码 -->
<input type="hidden" id="md5-password" name="password">
<button type="submit">submit</button>
</form>
<script>
function sub(){
alert('1');
let username = document.getElementById('username');
let pwd = document.getElementById('input-password');
let md5pwd = document.getElementById('md5-password');
md5pwd.value =calcMD5(pwd.value);
//判断内容是否符合要求,false提交失败
return true;
}
</script>
</body>
</html>
10. jQuery
jQuery is a fast, small, and feature-rich JavaScript library.
获取jQuery
-
方法一:本地导入
<script src = 'jquery.js'></script>
-
方法2:CDN导入
<!--导入jquery --> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
选择器
jQuery选择器使用格式
$(selector).action()
<body> <p>fefwf</p> <a href="#" id="id">rdgr</a> <div class="cls">fefefe</div> <script> $('.id').click(); $('#cls').click(); $('p').click(); </script> </body>
事件
-
鼠标事件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="lib/jquery-3.6.0.js"></script> </head> <body> <input type="button" id="hide" value="switch"> <div id="div1" style="width: 200px;height: 200px;border: 1px red solid;display: inline-block"><p class="cls1">mouseEvent</p></div> <div id="div2" style="height: 200px;width: 200px;border: 1px black solid;display: inline-block"> DIV2</div> <script> //$(function(){})网页加载后响应事件 $(function (){ //mousemove ,按键移动 $('#div1').mousemove(function (e){ $('.cls1').text(e.pageX +"-"+ e.pageY)}); }); //按下按键,div1消失 $('#hide').mousedown(function (){ $('#div1').slideToggle(); }); //鼠标穿过元素mouseenter $('#div2').mouseenter(function (){ $('#div1').hide(); }); //鼠标离开元素mouseleave $('#div1').mouseleave(function (){ $('.cls1').css("background","green"); }); //mouseout当鼠标指针从元素上移开 //mouseover当鼠标指针位于元素上方 //mouseup元素上放松鼠标按钮 </script> </body> </html>
-
操作DOM
文本节点操作
let li1 = $('#ul li[id = "li1"]').html();//获得html
$('#li2').html('<p style="font-size: 40px">JS</p>');//设置html
//text();
//text('element')
css操作
let li1 = $('#ul li[id = "li1"]');
let li2 = $('#li2');
li1.css('background','yellow');
li2.show();//显示
li2.hide();//隐藏