文章目录
一.HTML
1.常用标签
注释快捷键:ctrl+/
- 标题
<h1></h1>
和段落<P></p>
区块元素<div>
和<span>
- 换行
<br>
和水平线标签<hr>
- 文本格式化标签
- 图片的基本使用
<img src=" " alt = " " title=" ">
- 音频标签
<audio src=" " controls></audio>
6.视频标签
<video src=" " controls></video>
7.超链接
<a href=" " target ="_blank"> </a>
target =“ ”打开方式: -self当前页面打开 _blank新窗口打开
瞄点链接
<a href="#one">跳转</a>
2.表格
<table border="1" cellspacing="0">
<thead>
<tr><th>姓名</th><th>性别</th><th>年龄</th></tr>
</thead>
<tbody>
<tr><td>张三</td><td>男</td><td>20</td></tr>
<tr><td>李四</td><td>女</td><td>21</td></tr>
<tr><td>王五</td><td>男</td><td>22</td></tr>
</tbody>
</table>
合并单元格
- 跨行合并:rowspan=“合并单元格的个数”
(最上侧单元格为目标单元格,写合并代码) - 跨列合并:colspan=“合并单元格的个数”
(最左侧单元格为目标单元格,写合并代码)
3.列表
1.无序列表
<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>
- Coffee
- Milk
2.有序列表
<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>
- Coffee
- Milk
3.自定义列表
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
<dd>- white cold drink</dd>
</dl>
Coffee
4.表单
(1)input输入表单元素
- form 标签来创建表单
<form name="input" action="" method="get">
Username: <input type="text" name="user">
<input type="submit" value="Submit">
</form>
2.文本标签
文本域通过 <input type="text">
标签来设定,
<form>
First name: <input type="text" name="firstname" value ="张三"><br>
Last name: <input type="text" name="lastname">
</form>
value设置默认值
3.密码字段
密码字段通过标签 <input type="password">
来定义:
Password: <input type="password" name="pwd">
4.单选按钮
<input type="radio">
标签定义了表单的单选框选项
<form action="">
<input type="radio" name="sex" value="male">男<br>
<input type="radio" name="sex" value="female">女
</form>
注:单选框需要一样的name才能多选一
5.复选框
<input type="checkbox">
定义了复选框。
<form>
<input type="checkbox" name="vehicle" value="Bike">我喜欢自行车<br>
<input type="checkbox" name="vehicle" value="Car">我喜欢小汽车
</form>
6.input的属性
7.提交按钮
<input type="submit">
定义了提交按钮。
<input type="submit" value="提交">
8.重置按钮
<input type="submit">
定义了重置按钮。
<input type="reset" value="重置">
9.普通按钮
<input type="button">
定义了普通按钮。(结合js使用)
<input type="button" value="获取验证码">
10.文件域
<input type="file">
上传文件使用。
11.label标签
<label for="1">男</label>
<input type="radio" name ="sex" id="1"/>
可点击文字”男“,选中单选框
(3)select下拉表单元素
<select >
<option value="" selected="selected"></option>
<option value="0">北京</option>
<option value="1">上海</option>
<option value="2">广州</option>
<option value="3">深圳</option>
<option value="4">杭州</option>
</select>
selected=”seleced“默认选项
(4)textarea文本域元素
<textarea cols="50" rows="5"></textarea>
二.路径的使用
1. 绝对路径
2. 相对路径
-
同级路径
-
下级路径
-
上级路径
<img src="../目标图片.gif">
三.JavaScript
// 单行注释 ctrl+/
/*
多行注释 shitf+alt+a
*/
1.js的书写
1.行内式
<input type="button" value="点击问候" onclick="alert('你好')">
2.内嵌式
<script>
alert('hello');
</script>
3.外部js文件
<script src=" 文件名.js"></script>
2.js的输入输出语句
- 弹出框alert()
alert('hello')
2.输入框prompt()
var myname = prompt('请输入你的姓名');
alert(myname);
3.控制台输出console.log(’ ')
console.log('控制台可查看')
3.变量
1.变量的初始化
var age = 10,name = '张三';
2.声明变量的特殊情况
(1)只声明不赋值 结果:undefined
(2)不声明直接赋值 结果:可以使用
3.变量的命名规制
4.数据类型
js是动态语言,变量的数据类型是可以变化的
var x = 10;//x是数字型
x = 'hell';//x是字符串
1.数据类型介绍
(1)数字型 Number
var num1 = 010; //八进制
var num2 = 0x9; //十六进制
三个特殊的数字型
- infinity 代表无穷大
- -infinity 代表无穷小
- NAN 非数字
console.log('hello'-100);//结果NAN
isNAN判断是否是数字
console.log('isNaN(12)');//是数字返回false
console.log('isNaN('hello')');//true
(2)字符串型 String
//1.字符串长度
var String1 = "hello";
var String2 = 'world';//单引号和双引号均可,推荐使用单引号
console.log(String1.length);//length获取字符串长度
//2.字符串的拼接
var age =18;
console.log('我'+age+'岁');//结果:我18岁
console.log('我'+true);//true是布尔型,结果:你true
console.log(12+18);//30
console.log('12'+18);//1218
//3.外双内单,外单内双
var string3 = '你'好'啊'//报错
var string4 = '你"好"啊'//正确
var string4 = "你'好'啊"//正确
常用转义字符
(3)布尔型Boolean
var t = true;
var f = false;
console.log(t+1);//结果为2
console.log(f+1);//结果为1
(4)undefined和NUll
如果变量未赋值结果为undefined
//undefined
var value = undefined;
console.log(value + '你好');//undefined你好
console.log(value + 1);//NaN
//null
var space = null;
console.log(space + '你好');//null你好
console.log(space + 1);//1
console.log(true + 1);//1
(5)typeof 数据类型检测
var num = 10;
console.log(typeof num);//number
var value = undefined;
console.log(typeof value);//undefined
var space = null;
console.log(typeof space);//object
(6)数据类型转换
- 转换为字符串
var num = 10;
var str = num.tostring();
- 转换为数字型
//1.
var age = prompt('输入你的年龄');//age是字符型的
console.log(parseInt(age));//转换为整数
//2.数字+字符
console.log(parseInt('120px'));//120,数字在前可识别
console.log(parseInt('px120'));//NaN,数字在后不可识别
//3.Number()
var str = "123";
Number(str);//string转化为number
//4.隐式转换
console('120'-0);//数字型120
console('120'-'110');//10
console('120'*1);//120
- 转换为布尔型
// '',0,NaN,null,undefined均为false
//其余均为true
console.log(Boolean(''));//false
5.运算符
- 运算符的优先级
6.流程控制
- if…Else 语句
- switch 语句
- while循环
- do…while循环
- for循环
7.数组
1.创建数组
//1.var 数组名 = new Array();
var arr = new Array();
//2.
var arr = [1,2,'hello',true];//可以存任意类型
2.获取和遍历数组元素
var arr = [10,20,30];
alert(arr[1]);//20
alert(arr[10]);//undefined
//数组长度:数组名.length
for(var i=0;i<arr.length;i++){
console.log(arr[i]);
}
3.修改数组长度
1.
var arr = [10,20,30];
arr.length = 7;
2.
var newarr = [];//长度为0
newarr[0] = arr[0];//newarr长度变为1
newarr[newarr.length]=arr[1];//newarr长度为2
8.函数
使用关键字 function 定义函数。
1.声明函数和调用
//声明
function sum(a, b) {
return a * b; //没有return返回undefined
}
sum(2,3);
//函数表达式
var fun = function(){
console.log(22);
}
fun();//22
2.形参与实参不匹配
function sum(a, b) {
return a * b;
}
sum(2,3,4);//5,省略4
sum(2);//NaN
3.arguments
function fn() {
console.log(arguments);//存储了所以的实参
alertt(arguments[2]);
}
fn(1,2,3);//[1,2,3],结果为3
fn(4,5,6);//[4,5,6],结果为6
- 具有数组的length属性
- 按照索引的方式进行存储
- 没有数组的一些方法pop(),push()等
9.作用域
1.全局作用域
var num = 10;
console.log(num);//10
2.局部作用域
function sum(){
var num = 20; //局部变量
num2 = 1000; //全局变量,没有用var声明直接使用的变量是全局变量
console.log(num);//20
}
console.log(num);//10
3.javas没有块级作用域
function fn(){
var a = 1;
}
console.log(a);//可以使用,1
作用域链
var num = 10;
function fn(){
var num = 20;
function fun(){
alert(num); //20,就近原则
}
fun();
}
fn();
10.预解析
1.预解析:js里面的所以 var 还有function提升到当前作用域的最前面
- 变量提升,所以变量的声明提升到作用域最前面,但不提升赋值
- 函数提升,所以函数的声明提升到作用域最前面,但不调用
//1.变量
alert(num);//undefined
var num =100;
//2.函数
fun() //正确
function fun(){
alert(11);
}
fun2(); //报错
var fun2 = function(){
alert(100)
}
11.对象
对象由方法和属性组成
1.创建对象
1.对象字面量创建
var obj = {
name:'张三',
age:18,
sayHi:function(){
console.log('hi');
}
}
//两种调用属性
console.log(obj.name);
console.log(obj['age']);//加引号
//调用方法
obj.sayHi();
2.new创建对象
var obj2 = new object();
obj2.name = '李四'; //等号= 赋值添加对象的属性和方法
obj2.age = 18;
obj2.sayHi = function(){
console.log(hi);}
3.构造函数创建
function Fn(name,age,sex){ //规范:构造函数名首字母大写
this.name = name;
this.age = age;
this.sex = sex;
this.sing = function(sang){
alert(sang);
}
}
var w5 = new Fn('王五',18,'男');
var l6 = new Fn('老六',19,'女');
w5.sing('稻香');
alert(l6.name);
4.对象数组
```javascript
var student = [{
name:'张三';
sex:'男'
},{
name:'李四';
sex:'女'
}];
---
**2.遍历对象**
**for...in语句**对对象或数组进行循环操作
`for(变量 in 对象){}`
```javascript
var obj = {
name:'张三',
age:18,
sayHi:function(){
console.log('hi');
}
}
for(var k in obj){
console.log(k); //结果为属性名,name,age,sayHi
console.log(obj[k]);//结果为属性值
}
12.内置对象
APi查询MDN网站:https://developer.mozilla.org/zh-CN/
13.复杂数据类型
- 简单数据类型 null ,返回的是一个空的对象 object
var time = null;console.log('typeof timer');
结果为object
14.DOM
A.页面元素的获取
- (1) 通过Id获取getElementById(‘id名’)
<body>
<div id = "time">2001</div>
<script>
var timer =document.getElementById('time');//获得id="time"的标签
</script>
</body>
- (2) 通过标签获得getElementsByTagName(‘标签名’)
<body>
<ul>
<li>001</li>
<li>002</li>
</ul>
<script>
var list =document.getElementsByTagName('li');//获得全部li标签
console.log(list); //输出全部li标签,以伪数组形式存储
console.log(list[0]); //输出第一个<li>001</li>
2.
var ulist =document.getElementsByTagName('ul');//获取ul标签
ulist[0].getElementsByTagName('li');//获取第一个<ul>中的<li>
</script>
</body>
- (3) 类名获取(html5新增)getElementsByClassName(‘类名’)
<body>
<div class = "time">2001</div>
<div class = "time">2002</div>
<script>
var timer =document.getElementsByClassName('time');//获得class="time"的标签集合
</script>
</body>
- (4)选择器querySelector(‘选择器’)
返回指定选择器的第一个元素
<body>
<div class = "time">2001</div>
<div id = "list">
<ul>
<li>001</li>
<li>002</li>
</ul>
</div>
<script>
var query1 = document.querySelector('.time');//.选择第一个类名
var query2 = document.querySelector('#list');//#选择第一个id
var query3 = document.querySelector('li'); //选择第一个标签
</script>
</body>
- (5)querySelectorAll(‘选择器’)
返回一个集合
<body>
<div class = "time">2001</div>
<div class = "time">2002</div>
<script>
var timer =document.querySelectorAll('.time');//获得所以类名class,==getElementsByClassName(‘类名’)
</script>
</body>
- (6)获取
<body>
<html>
获取bodydocument.body
获取htmldocument.documentElement
B.事件基础
事件的三要素:
- (1)事件源,如
var btn = document.getElementById('id');
- (2)事件类型,如:鼠标点击onclick
- (3)事件处理程序,如:通过函数赋值
btn.onclick = function(){ alert('hello')}
<body>
<div>请点击</div>
<script>
var div = document.querySelector('div');
div.onclick = function(){
alert('hello');
<script>
}
</body>
C.操作元素
(1)修改内容和属性
1.改变元素内容
element.innerText
<body>//点击改变元素
<button>显示事件</button>
<div>时间</div>
<script>
//1.获取事件
var btn = document.querySelector('button');
var div = document.querySelector('div');
//2.注册事件
btn.onclick = function(){
div.innerText = '2022.11.13';
}
</script>
</body>
element.innerHTML
<body>
<div>hello</div>
<p>world</p>
<script>
var div = document.querySelector('div');
div.innerText = '今天是<strong>周末</strong>' //结果为今天是<strong>周末</strong>
//无法识别html标签,当读取时去除空格和换行,并去除html标签
var p = document.querySelector('p');
p.innerHTML = '今天是<strong>周六</strong>'//结果为今天是周六
//能识别html标签,当读取时保留空格,并保留html标签
</script>
</body>
2.改变元素属性
元素名.属性名
<body>//点击按钮改变图片属性
<button id = "one">图片1</button>
<button id = "two" >图片2</button>
<img src = "images/1.jpg" alt="">
<script>
//1.获取元素
var one = document.getElementBYId('one');
var two = document.getElementBYId('two');
var img1 = document.querySelector('img');
//2.注册事件
one.onclick = function(){
img1.src = 'images/1.jpg'; //元素.属性名;用引号包含起来
}
two.onclick = function(){
img1.src = 'images/2.jpg';
}
</script>
</body>
(2)修改表单
- 表单的值通过value属性改变
<body> //点击改变表单内容
<button>按钮</button>
<input type = "text" value = "请输入内容">
<script>
//1.获取元素
var but = document.querySelector('button');
var inp = document.querySelector('input');
//2.注册事件
but.onclick = function(){
//input.innerHTML = '点击了';//错误
inp.value = '点击了';
this.disabled = true;//不能再点击
}
</script>
</body>
(3)修改样式
- 1.通过style属性修改样式
<style>//点击<div>由粉色变红
div{
width : 200px;
height : 200px;
background-color : pink;
}
</style>
<body>
<i>x</i>
<div></div>
<script>
//1.获取元素
var div = document.querySelector('div');
var i = document.querySelector('i');
//2.绑定事件,点击变色
div.onclick = function(){
this.style.backgroundColor = 'red';
this.style.width = '250px';
}
//点击x隐藏div
i.onclick = function(){
div.style.display = 'none'; //block显示元素
}
</script>
</body>
- 2.通过修改className修改样式属性
元素名.className = '类名'
当修改样式较多时使用className
多类名保存
body>
<style> //样式
.first{
width : 200px;
height : 200px;
background-color : pink;
}
.change{
width : 500px;
height : 500px;
background-color : red;
}
</style>
<div class="first">hello</div>
<script>
//获取元素
var test = document.querySelector('div');
//绑定事件
test.onclick = function(){
// this.className = 'change';//类名 first改为change
this.className = 'first change';//first与change均保存
}
</script>
</body>
(4)操作元素总结
- 利用循环批量绑定事件
<body>
<button>1</button>
<button>2</button>
<button>3</button>
<script>
var btns = document.getElementsByTagName('button');
for(var i=0;i<btns.length;i++){
btns[i].onmouseover = function(){
for(var j=0;j<btns.length;j++){
btns[j].style.backgroundColor = ''; //把全部button颜色赋值为空
}
this.style.backgroundColor ='red'; //鼠标经过变红色
}
}
</script>
</body>
(5) 获取和设置属性的值
- 1.获取属性值
方法1:元素名.属性div1.id
方法2:元素名.getAttribute(‘属性’)div1.getAttribute('id')
区别:方法1只能获取HTML自带属性,方法2可以获得自己添加的属性
- 2.设置属性值
方法1:元素名.属性 = ’值‘div1.id = '1'
方法2:元素名.setAttribute(‘属性’,属性值)div1.setAttribute('id',2)
注:修改类名
1.div1.className = 'class1'
2.div1.setAttribute('class','class2')
//class特殊,不是className
- 移除属性removeAttribute(’属性‘)
div1.removeAttribute('id')
(6)自定义属性
目的:为了保存并使用数据
获取属性值:元素名.getAttribute('属性')
设置属性值:元素名.setAttribute('属性',属性值)
移除属性:元素名.removeAttribute(’属性‘)
H5规定:
data-
开头为自定义属性 如:data-index
H5新增的获取自定义属性的方法 元素名.dataset
datasetss是一个集合,存放了所以打他开头的自定义属性
dataset的使用,只能获取data-开头的,且有兼容性问题
div1.dataset.index
div1.dataset[index]
<body>
<style>
.item{
display: none;
}
</style>
<ul class="tab">
<li>首页</li>
<li>联系人</li>
<li>个人中心</li>
</ul>
<div class = "con">
<div class = "item" style="display: block">这是一个首页</div>
<div class = "item">你的好友列表</div>
<div class = "item">你的个人中心</div>
</div>
<script>
var tab = document.querySelector('.tab');
var list = tab.querySelectorAll('li'); //获取元素
for(var i = 0;i<list.length;i++){
list[i].setAttribute('data-index',i) //自定义属性,值为i
list[i].onclick =function(){ //绑定事件
//1.利用循环点击改变颜色
/* for(var i = 0;i<list.length;i++){
list[i].style.backgroundColor ='';
}
this.style.backgroundColor = 'red';*/
//2.利用自定义类,点击改变内容
var items =document.querySelectorAll('.item');
var index = this.getAttribute('data-index'); //获得自定义属性值
for(var i =0;i < items.length; i++){
items[i].style.display='none'; //全部设置为不可见
}
items[index].style.display = 'block';
}
}
</script>
</body>
D.节点操作
目的:获取元素
至少有:节点类型(nodeType),节点名称(nodeName),节点值(nodeValue)这三个基本属性
元素名.parentNode
返回最近节点,找不到返回null
元素名.childNodes
得到所以节点,包含元素节点,文本节点等,不提倡使用
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
var ul = document.querySelector('ul');
console.log(ul.childNodes);//9,回车算文本节点
console.log(ul.childNodes[0].nodeType);//结果为3,文本节点
2.元素名.children
只获得子元素节点,不包含文本节点等
可以当伪数组使用
3.元素名.firstChild
获得第一个节点,包含文本节点
4.元素名.firstElementChild
获得第一个子元素节点,不包含文本节点
注:有兼容性问题,ie9以上支持,可替换为:
元素名.children[0]
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
var ul = document.querySelector('ul');
<script>
console.log(ul.children[0]);
</script>
5.元素名.lastChild
获得最后一个节点,包含文本节点
6.元素名.lastElementChild
获得最后一个子元素节点,不包含文本节点
注:有兼容性问题,ie9以上支持,可替换为
元素名.children[元素名.chlildren.length-1]
下拉菜单
<body>
<style>
.nav ul{
display: none;
}
</style>
<Ul class="nav">
<li>
<a>动漫</a>
<ul>
<li>热门动漫</li>
<li>全部动漫</li>
</ul>
</li>
<li>
<a>电影</a>
<ul>
<li>热门电影</li>
<li>全部电影</li>
</ul>
</li>
<li>
<a>电视剧</a>
<ul>
<li>热门电视剧</li>
<li>全部电视剧</li>
</ul>
</li>
</Ul>
<script>
var nav = document.querySelector('.nav');
var list = nav.children; //获取nav的3个li标签
for(var i = 0;i<list.length;i++){
list[i].onmouseover = function(){ //鼠标经过显示
this.children[1].style.display = 'block'; //list下的第二个标签li
}
list[i].onmouseout = function(){ //鼠标移动消失
this.children[1].style.display = 'none';
}
}
</script>
</body>
(4)兄弟节点
- 下一个兄弟节点
nextSibling
包含 元素节点,文本节点等 - 上一个兄弟节点
previousSibling
包含元素节点,文本节点等
- 下一个兄弟节点
nextElementSibling
返回元素节点,不包含文本节点等 - 上一个兄弟节点
previousElementSibling
返回元素节点,不包含文本节点等
有兼容性问题,ie9以上才支持
解决方法:自己封装一个兼容性的函数
(5)动态创建,添加,删除节点
- 创建节点
document.createElement('li');
- 添加节点
1.元素名.appendChild(li);
//添加一个孩子节点,追加到后面
2.元素名.insertBefore(child,指定元素)
添加一个孩子节点,添加在指定节点前
<body>
<ul>
<li>hello</li>
</ul>
<script>
var ul = document.querySelector('ul')
var li1 = document.createElement('li'); //创建节点
ul.appendChild(li1); //添加节点,父节点之后
var li2 = document.createElement('li');
ul.insertBefore(li2,ul.children[0]);//添加节点,指定节点之前
ul.children[0].innerHTML = 'world' //添加内容
</script>
</body>
创建节点的拓展
- 删除节点
元素名.removeChild(li)
<body>
<button>1</button>
<ul>
<li>hello</li>
<li>world</li>
</ul>
<script>
//获取元素
var btn = document.querySelector('button');
var ul = document.querySelector('ul');
//绑定事件
btn.onclick = function(){
ul.removeChild(ul.children[0]) //删除第一个孩子节点
}
</script>
</body>
- 留言案例
<body>
<style>
li{
background-color: aqua;
height: 20px;
width: 300px;
margin: 15px;
}
li a{
background-color: brown;
float: right;
}
</style>
<textarea id="text"></textarea>
<button id="sub">发布</button>
<ul>
<li>hello world</li>
</ul>
<script>
//获取元素
var ul =document.querySelector('ul');
var text = document.getElementById('text');
var sub = document.getElementById('sub');
//绑定事件
sub.onclick = function(){
var li = document.createElement('li');
li.innerHTML = text.value +"<a herf = 'javascript:;' >删除</a>";
ul.appendChild(li); //创建并添加元素
var as = document.querySelectorAll('a');
for(var i=0 ;i<as.length;i++){
as[i].onclick = function(){
ul.removeChild(this.parentNode); //移除元素
}
}
}
</script>
</body>
(6)节点的复制
元素名.cloneNode()
括号内为空或false,只复制节点,不复制内容
括号内为true,复制节点和内容
<body>
<ul>
<li>节点复制</li>
</ul>
<script>
//获取元素
var ul = document.querySelector('ul');
//复制元素
var lione = ul.children[0].cloneNode(true);
//添加元素
ul.appendChild(lione);
</script>
</body>
(7)动态表格
<body>
<table border="1" >
<thead>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>操作</th>
</thead>
<tbody id="tb">
</tbody>
</table>
<script>
var student = [{
name:'张三',
sex:'男',
Age:18
},{
name:'李四',
sex:'女',
age:19
}];
var tb =document.getElementById('tb');
for(var i=0;i<student.length;i++){
var trs = document.createElement('tr'); //创建行
tb.appendChild(trs);
for(var k in student[i]){ //遍历对象
var th = document.createElement('td') //创建单元格
trs.appendChild(th);
th.innerHTML = student[i][k]; //student[i][k]数据填充
}
var del =document.createElement('td'); //创建删除单元格
del.innerHTML = '<a href="javascript:;"">删除</a>';
trs.appendChild(del);
}
var as = document.querySelectorAll('a');
for(var i=0;i<as.length;i++){
as[i].onclick =function(){ //绑定删除操作
tb.removeChild(this.parentNode.parentNode);
}
}
</script>
</body>
(8)DOM的重点总结
1.创建
- document.write
- innerHTML
- createElement
2.增加到页面
- appendChild
- insertBefore
3.改
-
改变元素内容
element.innerText
-
表单的值通过value属性改变
-
改变元素属性
element.属性名
-
通过style属性修改样式
this.style.width = '250px';
-
通过修改className修改样式属性
元素名.className = '类名'
4.查
5.事件操作
15.事件高级
A.绑定事件
给元素添加事件,称为注册事件或者绑定事件
注册事件有两种方式:传统方法和方法监听注册方法
- 传统注册方法
利用 on 开头的事件 如:onclick
1.<button onclick = "alert('hi~')"></button>
2.元素名.onclick = function(){}
特点:注册事件的唯一性
同一个元素同一个事件只能设置一个处理函数,最后注册的处理函数将会覆盖前面的注册的处理函数
- 方法监听注册方式
addEventListener()
注:IE9之前的IE不支持此方法,可使用attachEvent()代替
特点:同一个元素同一个事件可以注册多个监听器
按注册顺序依次进行
eventTarget.addEventListener(type,listener[,useCapture])
该方法接收的三个参数
- type:事件类型字符串, 如:click,mouseover,注意这里不带on
- listener:事件处理函数,事件发生时,会调用该监听函数
- usecapture:可选参数,是一个布尔值,默认为false
<body>
<button>监听测试</button>
<script>
var btn = document.querySelector('button');
//第一个监听事件
btn.addEventListener('click',function(){
alert('hello world');
})
//第二个监听事件
btn.addEventListener('click',function(){
alert('hi~');
})
</script>
</body>
- attachEvent事件监听(了解即可)
eventTarget.attachEvent(eventNameWithOn,callback)
注:IE9之后不可使用,不提倡使用
- eventNameWithOn:shij类型字符串,比如onclick,onmouseover,这里要带on
- callback:事件处理函数,当目标触发事件时回调函数被调用
<body>
<button>attachEvent监听测试</button>
<script>
//事件监听
var btn = document.querySelector('button');
btn.attachEvent('onclick',function(){
alert('hello world')
})
btn.attachEvent('onclick',function(){
alert('hi~');
})
</script>
</body>
B.解绑事件
元素名.onclick = null
removeEventListener
ie9后detachEvent
ie9前
<body>
<div>hello</div>
<div>world</div>
<div>hi</div>
<script>
var divs = document.querySelectorAll('div');
//传统事件注册,删除事件
divs[0].onclick = function(){
alert('hi~');
divs[0].onclick =null; //通过null
}
//监听事件
divs[1].addEventListener('click',fn) //fn不加(括号)
function fn(){
alert('world');
divs[1].removeEventListener('click',fn);//removeEventListener删除事件
}
</script>
</body>
C.事件流冒泡与捕获
- 事件捕获和事件冒泡
D.事件对象
1.是事件对象,写到侦听函数的小括号里面当形参
2.事件对象之一事件才存在,由系统创建,不需要传递参数
3.事件对象 包含一系列相关数据
注:ie9前用window.event
兼容性解决event = event || window.event
<body>
<div>事件对象</div>
<script>
var div =document.querySelector('div');
div.onclick = function(event){ //event名可以任意更改
console.log(event); //输出一系列相关数据
}
</script>
</body>
(1)返回对象
- this和event的区别:e.target点击元素返回点击的元素,this返回绑定的事件元素
<body>
<ul>
<li>one</li>
<li>two</li>
</ul>
<script>
var ul =document.querySelector('ul');
//监听事件绑定
ul.addEventListener('click',function(e){
console.log(this); //点击li时(冒泡),返回 ul
console.log(e.target); //点击li时,返回 li
})
</script>
</body>
(2) 阻止默认行为
preventDefaukt()
<body>
<a href="https://www.baidu.com/">监听注册阻止默认事件</a>
<a href="https://www.baidu.com/" >传统注册阻止默认事件</a>
<script>
var a =document.querySelectorAll('a');
//监听事件
a[0].addEventListener('click',function(e){
e.preventDefault();
})
//传统事件
a[1].onclick = function(e){
e.preventDefault(); //阻止默认事件,ie9后使用
//e.returnValue; //ie9前使用
//return false; //通用,但无法执行后的alert(!)
alert(1);
}
</script>
</body>
(3) 阻止冒泡
e.stopPropagation();
ie9之前不兼容使用
<body>
<ul>
<li>one</li>
<li>two</li>
</ul>
<script>
var ul =document.querySelector('ul');
//监听事件绑定
ul.addEventListener('click',function(e){
alert('ui');
})
var li =ul.children;
li[0].onclick = function(e){
alert('li');
e.stopPropagation(); //结果为li,将不在执行冒泡
//不阻止冒泡,结果为li,ul
}
</script>
</body>
e.cancelBubble() = true
IE9之前使用(了解即可)
(4)事件委托
不是给每个子节点添加事件监听器,而且事件监听器设置在父节点上,如何利用冒泡原理设置每个子节点。效率更高
<body>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<script>
var ul =document.querySelector('ul');
ul.addEventListener('click',function(e){
//点击li标签变为红色
e.target.style.backgroundColor = 'red'; //利用冒泡和target完成事件委托
})
</script>
</body>
(5)鼠标事件拓展
基础鼠标事件
- 1.禁止鼠标右键
contextmenu
<body>
<script>
document.addEventListener('contextmenu',function(e){ //document表示整个页面
e.preventDefault(); //阻止contextmenu事件
})
</script>
</body>
- 2.禁止鼠标选中
selectstart
<body>
<div>禁止选中</div>
<p>可以选择</p>
<script>
var div =document.querySelector('div');
div.addEventListener('selectstart',function(e){
e.preventDefault(); //禁止div的selectstart默认事件
})
</script>
</body>
- 获取页面的坐标
获取鼠标的坐标
<script>
document.addEventListener('click',function(e){
console.log(e.clientX); //输出x坐标
console.log(e.clientY);//输出y坐标
})
</script>
- 鼠标跟踪案例
<body>
<style>
div{
position: absolute;
}
</style>
<div>我是一个鼠标</div>
<script>
var div =document.querySelector('div');
document.addEventListener('mousemove',function(e){
var x = e.pageX;
var y = e.pageY; //每次鼠标移动获得最新坐标
console.log('x的坐标是:'+ x+',y的坐标是:'+y);
div.style.left = x + 'px'; //px一定要加
div.style.top = y + 'px';
})
</script>
</body>
(6)键盘事件
keypress和keyup的区别:
- 两个同时存在优先执行keypress,
- 使用keycode属性时keyup不区分大小写.
- keypress区分大小写
//监听事件
document.addEventListener('keydown',function(){ //注意监听事件不加on
console.log('按钮被按下');
})
//传统事件
document.onkeyup =function(){
console.log('松开了按钮');
}
- 键盘的对象
判断按下的按钮key和keycode
注: key有兼容性问题,keycode返回ascll码值
<input type = "text">
<script>
var search = document.querySelector('input');
//监听事件
document.addEventListener('keyup',function(e){
console.log(e.keyCode); //输出按下按键的ASCLL码值
if(e.keyCode === 83){ //判断等于s,鼠标焦点在input标签
search.focus();
}
})
</script>
16.BOM
A.页面和窗口
<script>
var btn = document.querySelector('button');
btn.onclick = function(){
alert('触发了'); //无法被触发,页面从上往下执行
}
</script>
<button>按钮</button>
- 页面加载onload
window.onload = function(){}
window.addEventListener('load',function(){})
页面完全加载后触发,可放在任意位置
<body>
<script>
window.onload=function(){ //页面加载完成后触发
var btn = document.querySelector('button');
btn.onclick = function(){
alert('触发了'); //可以被触发
}
}
<button>按钮</button>
</script>
</body>
- 窗口加载DOMContentLoaded
document.addEventListener('DOMContentLoaded',function(){})
- load等页面内容全部加载完毕,包含dom元素,图片,flash,css等
- DOMContentLoaded是DOM加载完毕,不包含图片,flash,css等就可以执行,加载速度比load更快一点
<body>
<script>
window.addEventListener('load',function(){
var btn =document.querySelector('button');
btn.addEventListener('click',function(){
alert('按钮被触发');
})
})
window.addEventListener('load',function(){ //注意开头用的window
alert('页面加载完毕');
})
//DOM加载
document.addEventListener('DOMContentLoaded',function(){
alert('DOM加载完毕');
})
//执行顺序:DOM加载完毕》页面加载完毕
</script>
<button>按钮</button>
</body>
- 窗口大小调整resize
窗口调整大小时触发
document.addEventListener('resize',function(){})
<body>
<script>
//load页面加载后执行
window.addEventListener('load',function(){
var div =document.querySelector('div');
//resize调整窗口大小触发
window.addEventListener('resize',function(){
console.log(window.innerWidth);
if(window.innerWidth <= 800){ //div宽度小于800消失
div.style.display = 'none';
}else{
div.style.display='block';
}
})
})
</script>
<div >缩小窗口消失</div>
</body>
B.定时器
(1)设置定时器setTimeout()
window.setTimeout(调用函数,延时时间)
window可以省略
延时时间可以省略默认为0,单位毫秒
<script>
function callback(){
alert('该睡觉了');
}
//2秒后弹出
setTimeout(callback,2000);
//写法2:不推荐使用
setTimeout('callback()',5000);
</script>
(2) 停止定时器clearTimeout()
clearTimeout(定时器)
<body>
<button>学个屁</button>
<script>
//设置定时器
var timer = setTimeout(function (){
alert('该去学习了');
},2000);
//设置点击事件,清除定时器
var btn =document.querySelector('button');
btn.addEventListener('click',function(){
clearTimeout(timer);
})
</script>
</body>
(3)重复调用定时器setInterval()
window.setInterval(回调函数,间隔的毫秒数)
- window可以省略
- 调用时:1.直接写函数,2.写函数名,3.采用字符串‘函数名()’
- 间隔的毫秒数可以省略,默认为0毫秒
setInterval()与setTimeout()的区别
- setInterval()方法重复调用一个函数,每隔这个时间,调用依次
setTimeout()值调用一次
//每隔2秒弹出一次
setInterval(function (){
alert('该去睡觉了');
},2000);
(4)清楚重复定时器clearInterval()
clearInterval(定时器名)
<button>学个屁</button>
<script>
//设置间隔定时器
var timer = setInterval(function study(){
alert('该去学习了');
},2000);
//设置点击事件,清除定时器
var btn =document.querySelector('button');
btn.addEventListener('click',function(){
clearInterval(timer);
})
</script>
- 定时器总结
验证码接收案例
<body>
<input type="text" placeholder="请输入验证码">
<input type = "button" value="点击发送验证码">
<script>
var btn =document.querySelectorAll('input');
var time = 5;
//绑定点击事件
btn[1].addEventListener('click',function(){
btn[1].disabled =true; //点击后设置按钮不可用
//设置定时器
var timer = setInterval(function(){
btn[1].value ="还剩"+time+"秒";
time--;
if(time <= 0){
btn[1].value ="点击发送验证码"
btn[1].disabled =false; //满足条件后按钮可用
time =5;
clearInterval(timer); //清除定时器
alert('请重新获取验证码');
}
},1000);
})
</script>
</body>
c.this的指向问题
- 1.全局作用域或者普通函数中的this指向全局对象window
<script>
//1.
console.log(this); //指向window
//2.
function fn(){
console.log(this); //指向window
}
//调用函数,window可以省略
window.fn();
//3.window可以省略
window.setTimeout(function(){
console.log(this); //指向window
},1000);
</script>
- 2.方法中的this,谁调用指向谁
//1.
var o = {
sayHI:function(){
console.log(this);//指向o这个对象
}
}
//2.
btn.onclick = function(){
console.log(this); //指向btn这个按钮对象
}
- 3.构造函数中this,指向构造函数的实例
function Fun(){
consloe.log(this); //指向实例对象f
}
var f = new Fun();
D.JS的同步和异步
- 同步:前一个执行结束后再执行下一个
- 异步:同时做多个任务
E.location对象
获得和设置URL
URL:统一资源定位符tongyizhiyuandinwei
- location对象属性
<body>
<button>改变href</button>
<div></div>
<script>
//获取元素
var btn =document.querySelector('button');
var div =document.querySelector('div');
var time = 5;
//绑定事件
btn.addEventListener('click',function(){
setInterval(function(){
if(time == 0){
location.href = 'https://www.baidu.com/'; //改变href值,跳转页面
}else{
div.innerHTML =time+'秒后将为您跳转到百度';
time--;
}
},1000)
})
</script>
</body>
- location对象方法
F.navigator对象
包含浏览器的相关信息
判断是电脑浏览器还是手机浏览器
G.history对象
对历史记录进行交互
17.pc端网页特效
A.offset获取元素信息
动态的获取元素的位置的,大小等
- 获取元素距离带有定位父元素的位置
- 获得元素自身的大小(宽度高度)随边框大小变化
- 注意:返回的数值是不带单位的
<body>
<div style="margin: 500px " >hello world</div>
<script>
var father =document.querySelector('div');
alert(father.offsetTop); //500
</script>
</body>
offset 与style的区别
<body>
div{
position: fixed;
height: 200px;
width: 200px;
background-color: red;
}
<div >hello world</div>
<script>
var div =document.querySelector('div');
//点击改变div的位置
div.addEventListener('mousedown',function(e){
div.style.margin = 100+ 'px';
})
</script>
</body>
鼠标拖动盒子
<body>
<div >hello world</div>
<script>
var div =document.querySelector('div');
div.addEventListener('mousedown',function(e){
var x = e.pageX - div.offsetLeft;
var y = e.pageY - div.offsetTop;
div.innerHTML=x+','+y;
document.addEventListener('mousemove',move)
function move(e){
div.style.left = e.pageX- x + 'px';
div.style.top = e.pageY- y + 'px';
}
document.addEventListener('mouseup',function(){
document.removeEventListener('mousemove',move);
})
})
</script>
</body>
B.client获取元素信息
获取元素可视区的相关信息,通过相关属性获得该元素的边框大小,元素大小
client
和offset
获得元素大小的区别:client不包含边框
C.立即执行函数
不需要调用,能够自己执行的函数
立即执行函数最大的作用是:独立创建了一个作用域,里面所以的变量都是局部变量,不会命名冲突
//1.普通函数
function fn(){
alert('hello');
}
fn();
//2.立即执行函数
//写法1.第二个小括号可以看作是调用函数
(function(a) {
alert('hi');
})('hi')
//写法2.
(function(a,b){
alert(a+b); //3
}(1,2))
D.scroll元素滚动
动态获取元素的大小,滚动距离等
scroll和client获得元素大小的区别:当内容大于自身时scroll会变化,client获取元素大小保持不变
如:
scrollHeight变为283,clientHeight保持不变
给超出部分添加滚动条时:
- 鼠标事件:onscroll滚动条变化时触发
E.三大系列总结
F.mouseenter和mouseover的区别
mouseenter类似与mouseover移动到元素上触发
区别:
- mouseover鼠标经过自身盒子会触发,经过子盒子也会触发
- mouseenter只经过自身盒子触发
原因:mouseenter不会触发冒泡
G.动画
(1)动画的原理
核心原理:通过定时器
setInterval()
不端移动盒子
<style>
div{
position:absolute;
width: 200px;
height: 200px;
background-color: red;
}
</style>
<body>
<div></div>
<script>
var div =document.querySelector('div');
//设置定时器,每秒向右移动100px
var timer=setInterval(function(){
if(div.offsetLeft>=500){ //满足条件结束动画
clearInterval(timer);
}
div.style.left =div.offsetLeft +100+'px'; //style.left设置元素
//offsetleft获取元素
},1000)
</script>
</body>
(2)动画封装函数
<style>
div{
position:absolute;
width: 200px;
height: 200px;
background-color: red;
}
</style>
<body>
<button>点击运行</button>
<div></div>
<script>
//封装函数,obj目标对象,T目标位置
function a(obj,T){
//当我们不断的点击按钮,这个元素会越来越快
//因为开启太多的定时器
//解决方案:清除以前的定时器
clearInterval(obj.timer);
//设置定时器,obj.timer方便创建多个对象
obj.timer=setInterval(function (){
if(obj.offsetLeft>=T){
clearInterval(obj.timer);
}else{
div.style.left =div.offsetLeft +20+'px';
}
},200)
}
var div =document.querySelector('div');
var btn =document.querySelector('button');
//点击按钮移动盒子
btn.addEventListener('click',function(){
a(div,500);
})
</script>
</body>
- 缓动动画
让元素的运动速度有所变化
<style>
div{
position:absolute;
width: 200px;
height: 200px;
background-color: red;
}
</style>
<body>
<button>点击运行</button>
<div></div>
<script>
//封装函数
function a(obj,T){
clearInterval(obj.timer);
//设置定时器
obj.timer=setInterval(function (){
var step =(T-obj.offsetLeft)/10; //通过step实现缓慢停止效果
if(obj.offsetLeft>=T){
clearInterval(obj.timer);
}else{
div.style.left =div.offsetLeft +step+'px';//将固定值,更该为变化的step
}
},200)
}
var div =document.querySelector('div');
var btn =document.querySelector('button');
//点击按钮移动盒子
btn.addEventListener('click',function(){
a(div,500);
})
</script>
</body>
- 动画函数多个值来回移动
Math.ceil()向上取整
Math.floor()向下取整
<style>
div{
position:absolute;
width: 200px;
height: 200px;
background-color: red;
}
</style>
<body>
<button>点击移动到500</button>
<button>点击移动到800</button>
<div></div>
<script>
//封装函数
function a(obj,T){
clearInterval(obj.timer);
//设置定时器
obj.timer=setInterval(function (){
var step =(T-obj.offsetLeft)/10;
step =step>0 ? Math.ceil(step) : Math.floor(step);//消除误差
if(obj.offsetLeft==T){
clearInterval(obj.timer);
}else{
div.style.left =div.offsetLeft +step+'px';
}
},10)
}
var div =document.querySelector('div');
var btn =document.querySelectorAll('button');
//设置多个点击事件,点击移动盒子
btn[0].addEventListener('click',function(){
a(div,500);
})
btn[1].addEventListener('click',function(){
a(div,800);
})
</script>
</body>
- 动画函数添加回调函数
原理:函数作为一个参数,将这个函数作为参数传到另一个函数里面,当那个函数执行完之后,再执行传进去的这个函数,这个过程叫回调
<style>
div{
position:absolute;
width: 200px;
height: 200px;
background-color: red;
}
</style>
<body>
<button>点击移动到500</button>
<button>点击移动到800</button>
<div></div>
<script>
//封装函数
function a(obj,T,end){
clearInterval(obj.timer);
//设置定时器
obj.timer=setInterval(function (){
var step =(T-obj.offsetLeft)/10;
step =step>0 ? Math.ceil(step) : Math.floor(step);
if(obj.offsetLeft==T){
clearInterval(obj.timer);
if(end){ //函数结束执行,判断end是否存在
end(); //将背景颜色变为绿色
}
}else{
div.style.left =div.offsetLeft +step+'px';
}
},10)
}
var div =document.querySelector('div');
var btn =document.querySelectorAll('button');
//绑定点击事件,点击移动盒子
btn[0].addEventListener('click',function(){
a(div,500,function(){
div.style.backgroundColor='green'; //将函数作为参数
});
})
btn[1].addEventListener('click',function(){
a(div,800);
})
</script>
</body>
- 将动画函数封装到js文件里面
1.单独创建一个js文件,将写好的函数放入
2.在需要使用的文件内引入<script src="文件名.js"></script>
18.移动端网页特效
A.touch触摸事件
<style>
div{
position:absolute;
width: 200px;
height: 200px;
background-color: red;
}
</style>
<body>
<div></div>
<script>
var div =document.querySelector('div');
//绑定事件
div.addEventListener('touchstart',function(){ //触摸触发事件
alert('hello');
})
</script>
</body>
- 触摸事件对象的常用属性
- touches和targetTouches如果侦听的是同一个元素就没有区别
- 手指离开,就没有touches和targetTouches但会有changedTouches
<style>
div{
position:absolute;
width: 200px;
height: 200px;
background-color: red;
}
</style>
<body>
<div></div>
<script>
var div =document.querySelector('div');
//绑定触摸事件对象
div.addEventListener('touchstart',function(e){
console.log(e.targetTouches);//获得正在触摸dom元素的第一个手指相关信息,如手指的坐标
})
</script>
</body>
- 移动端拖动元素
<style>
div{
position: fixed;
height: 200px;
width: 200px;
background-color: red;
}
</style>
<body>
<div >hello world</div>
<script>
//
var touchx = 0;
var touchy = 0;
var x = 0;
var y = 0
var div = document.querySelector('div');
//绑定事件
div.addEventListener('touchstart',function(e){
touchx = e.targetTouches[0].pageX;//获取手指的初始坐标
touchy = e.targetTouches[0].pageY;
x = this.offsetLeft; //获取盒子的初始坐标
y = this.offsetTop;
})
div.addEventListener('touchmove',function(e){
var movex = e.targetTouches[0].pageX-touchx; //获取移动的距离
var movey = e.targetTouches[0].pageY-touchy;
this.style.left = x + movex +'px'; //移动盒子
this.style.top = y + movey + 'px';
e.preventDefault();
})
</script>
</body>
B.移动端300ms延时问题
1.
C.插件
(1)Swiper插件
js插件是js文件
- 1.引入j
<script src="文件名.js"></script>
- 2.引入css
<link rel="styleSheet" href="文件名.css">
- 3.按语法规范使用
(2)其他插件
D.框架
19.本地存储
本地存储的特性
- 1.数据存储在用户浏览器中
- 2.设置,读取方便,甚至页面刷新不丢失数据
- 3.容量较大,sessionStorage约5M,localstorage约20M
- 4.只能存储字符串,考研将对象json.stringify()编码后存储
A.window.sessionStorage
- 1.生命周期为关闭浏览器窗口
- 2.在同一窗口(页面)下数据可以共享
+3.以键值对的形式存储使用
- 1.存储数据
sessionStorage.setItem(key,value)
- 2.获取数据
sessionStorage.getItem(key)
- 3.删除数据
sessionStorage.removeItem(key)
- 4.删除所以数据
sessionStorage.clear()
<body>
<input type="text">
<button class="set">存储数据</button>
<button class="get">获取数据</button>
<button class="remove">删除数据</button>
<button class="del">清空所以数据</button>
<script>
//点击存储数据
var inp = document.querySelector('input');
var set = document.querySelector('.set');
set.addEventListener('click',function(){
var value = inp.value;
sessionStorage.setItem('uname',value);
})
//点击获取数据
var get = document.querySelector('.get');
get.addEventListener('click',function(){
console.log(sessionStorage.getItem('uname'));
})
//点击删除数据
var rem = document.querySelector('.remove');
rem.addEventListener('click',function(){
sessionStorage.removeItem('uname');
})
</script>
</body>
B.window.localStorage
1.生命周期永久生效,除非手动删除否则关闭页面也存在
2.可以多窗口(页面)共享(同一浏览器可以共享)
3.以键值对的形式存储使用
- 1.存储数据
localStorage.setItem(key,value)
- 2.获取数据
localStorage.getItem(key)
- 3.删除数据
localStorage.removeItem(key)
- 4.删除所以数据
localStorage.clear()
<body>
<input type="text">
<button class="set">存储数据</button>
<button class="get">获取数据</button>
<button class="remove">删除数据</button>
<button class="del">清空所以数据</button>
<script>
//点击存储数据
var inp = document.querySelector('input');
var set = document.querySelector('.set');
set.addEventListener('click',function(){
var value = inp.value;
localStorage.setItem('uname',value);
})
//点击获取数据
var get = document.querySelector('.get');
get.addEventListener('click',function(){
console.log(localStorage.getItem('uname'));
})
//点击删除数据
var rem = document.querySelector('.remove');
rem.addEventListener('click',function(){
localStorage.removeItem('uname');
})
</script>
</body>
20.jQuery
$ 是jQuery的别称
A.入口函数
- 1.等着DOM结果渲染完成再执行内部代码,不必等到外部所以资源加载完成
- 2.相当于js的DOMContentLoaded
- 3.不同于js的load事件,load是等页面文档,外部js,css,图片等加载完才执行内部代码
//两种方法相等
1.
$(document).ready(function(){......});
2.//简写
$(function(){......});
B.DOM对象与jQuery对象
(1)基本使用
- jQuery对象只能使用jQuery方法
- DOM方对象只能使用javascript的方法和属性
- jQuerys的本质是通过封装DOM元素进行包装
<body>
<div>hello</div>
<script>
//dom方式获取元素
var myDiv = document.querySelector('div');
console.dir(myDiv);
//jQuery方式获取元素
console.dir($('div'));//伪数组形式
</script>
</body>
(2) DOM和jQuery的相互转换
- 1.DOM转jQuery
$(DOM名)
DOM对象只能使用javascript的方法和属性,想使用jquery方法需要转换
<body>
<div>hello</div>
<script>
var myDiv = document.querySelector('div');
$(myDiv).hide(); //将DOM转换为jQuery
</script>
</body>
- 2.jQuery转DOM
两种方式
1.$('元素')[索引号]
,2.$('元素').get(索引号)
<body>
<div>hello</div>
<script>
//1.伪数组方式
$('div')[0].style.display = 'none';
//2.
$('div').get(0).style.display ='none';
</script>
C.jQuery的API
(1) jQuery的选择器
a.基本选择器
b.层级选择器
- 3.筛选选择器
c.基础筛选
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<script>
//:first
$("ul li:first").css("color","blue");//1改为蓝色
//:eq()
$("ul li:eq(1)").css("color","blue");//2改为蓝色
//:last
$("ul li:last").css("color","pink"); //将c改为粉色,ul的最后一个元素
$("ul:eq(0) li:last").css("color","red");//将3改为红色
//:even
$("ul:eq(1) li:even").css("background","red"); //偶数AC,背景改为红色
$("ul:eq(1) li:even").css("height","100px"); //偶数AC,高度改为100px
$("ul:eq(1) li:even").css("width","100px"); //偶数AC,宽度改为100px
</script>
</body>
d.父子筛选
parents()查找所以的父级
<body>
<div class="baba">
<p class="erzi">1</p>
<div>
<p class="sunzi">2</p>
</div>
</div>
<script>
//父级
$(".sunzi").parent().css("background","red");//最近一级,2背景变为红色
//子级
$(".baba").children("p").css("color","blue");//只包含儿子不包含孙子,1颜色变为蓝色
$(".baba").find("p").css("height","100px") //包含儿子和孙子,1和2高度改为100px
</script>
</body>
jQuery完成下拉菜单
<style>
ul li ul{display: none; }
.nav li{float:left;width:100px;} //横向显示
</style>
<body>
<ul class="nav">
<li>
<a href="">数字</a>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</li>
<li>
<a href="">字母</a>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
</li>
<li>
<a href="">英文</a>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</li>
<script>
//入口函数
$(function(){
//绑定事件,鼠标移动
$(".nav>li").mouseover(function(){//.nav>li选择子元素
$(this).children("ul").show(); //显示
})
//绑定事件,鼠标离开
$(".nav>li").mouseout(function(){
$(this).children("ul").hide(); //隐藏
})
})
</script>
</body>
e.兄弟筛选
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script>
$("ul li:first").siblings("li").css("color","red");//234改变颜色
$("ul li:eq(1)").nextAll("li").css("color","red");//34改变颜色
$("ul li:eq(1)").prevAll("li").css("color","red"); //1改变颜色
$("ul li").eq(1).css("color","red"); //2改变颜色
</script>
</body>
隐式迭代
<body>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<script>
//排他思想
$("button").click(function(){
$(this).css("background","red");//鼠标点击变为红色
$(this).siblings("button").css("background","");//将兄弟节点颜色删除
});
</script>
</body>
链式编程
//可将上面代码改为
$("button").click(function(){
$(this).css("background","red").siblings("button").css("background","");
});
(2)jQuery修改css样式
a. 通过jQuery修改css的方法
- 属性名必须加引号,逗号分隔,值如果是数字可以不加引号和单位
$("div").css("width")
只写属性名,返回属性值$("div").css("width","300px")
写属性名和值,修改属性值
- 设置多个值,以对象的形式
属性引号可加可不加,值不是数字必须加引号
$(this).css({width:400,height:400,backgroundColor:"red" })
b.通过jQuery操作css类
<style>
.myDiv{
position: fixed;
height: 200px;
width: 200px;
background-color: red;
}
</style>
<body>
<div>hello</div>
<span>world</span>
<script>
//添加类
$("div").mouseover(function(){
$(this).addClass("myDiv");
})
//删除类
$("div").mouseout(function(){
$(this).removeClass("myDiv");
})
//切换类
$("span").click(function(){
$(this).toggleClass("myDiv");//点击添加类,再点击删除类
})
</script>
案例:tag栏切换
<style>
div p{
display: none;
}
.nav li{float:left;width:100px;}
.list{
background-color: red;
}
</style>
<body>
<ul class="nav">
<li>
数字
</li>
<li>
字母
</li>
<li>
英文
</li>
</ul>
<br>
<div class="ls">
<p>1</p>
<p>A</p>
<p>one</p>
</div>
<script>
//绑定点击事件
$(".nav li").click(function(){
//链式添加移除类
$(this).addClass("list").siblings().removeClass("list");
//获得索引号
var index = $(this).index();
//链式显示隐藏
$(".ls p").eq(index).show().siblings().hide();
})
</script>
</body>
c.jQuery类操作和className的区别
className会覆盖原先的类名
jQuery只对指定类进行操作,不影响原先的类名
<body>
<div class="one">hello</div>
<script>
var cN = document.querySelector("div");
cN.className = "two"; //two,覆盖原有类名
$("div").addClass("three"); //two three,再two的基础上添加three
$("div").removeClass("three"); //two,移除three
</script>
(3)jQuery动画效果
a.显示和隐藏
- show()
- hide()
- toggle()
<style>
div{
position: fixed;
height: 200px;
width: 200px;
background-color: red;
}
</style>
<body>
<button>显示</button>
<button>隐藏</button>
<button>切换</button>
<div>hello</div>
<script>
//点击显示
$("button").eq(0).click(function(){
$("div").show(1000,function(){
console.log("显示");
});
})
//点击隐藏
$("button").eq(1).click(function(){
$("div").hide("slow",function(){
console.log("隐藏");
});
})
//点击切换显示与隐藏
$("button").eq(2).click(function(){
$("div").toggle();
})
</script>
</body>
b.滑动
- sildedown()
- sildeup()
- sildeToggle()
<style>
div{
position: fixed;
height: 200px;
width: 200px;
background-color: red;
}
</style>
<body>
<button>显示</button>
<button>隐藏</button>
<button>切换</button>
<div>hello</div>
<script>
//点击显示
$("button").eq(0).click(function(){
$("div").slideDown(1000,function(){ //滑动显示
console.log("显示");
});
})
//点击隐藏
$("button").eq(1).click(function(){
$("div").slideUp("slow",function(){//滑动隐藏
console.log("隐藏");
});
})
//点击切换
$("button").eq(2).click(function(){
$("div").slideToggle(); //滑动切换显示与隐藏
})
</script>
</body>
c.事件切换
<style>
div{
height: 200px;
width: 200px;
background-color: red;
}
</style>
<body>
<button>hover切换1</button>
<button>hover切换2</button>
<div>hello</div>
<script>
//
$("button").eq(0).hover(function(){
$("div").slideDown(); //鼠标经过,滑动显示
},function(){
$("div").slideUp(); //鼠标离开,滑动隐藏
})
$("button").eq(1).hover(function(){
$("div").slideToggle(); //无论鼠标经过还是离开都会触发
})
</script>
</body>
d.动画停止
<button>hover切换</button>
<div>hello</div>
<script>
$("button").hover(function(){
$("div").stop().slideToggle();//先停止,在执行切换
})
</script>
e.淡入淡出与透明度
- fadeIn()
- fadeOut()
- fadeToggle()
- fadeTo
<style>
div{
position: fixed;
height: 200px;
width: 200px;
background-color: red;
}
</style>
<body>
<button>淡入</button>
<button>淡出</button>
<button>切换</button>
<div>hello</div>
<script>
//点击淡入
$("button").eq(0).click(function(){
$("div").fadeIn(1000);
})
//点击淡出
$("button").eq(1).click(function(){
$("div").fadeOut(1000);
})
//点击淡入淡出切换
$("button").eq(2).click(function(){
$("div").fadeToggle(1000);
})
</script>
</body>
注:速度与透明度必须写
<style>
div{
background-color: red;
}
</style>
<body>
<button>修改透明度</button>
<div>hello</div>
<script>
//点击修改透明度
$("button").click(function(){
$("div").fadeTo(1000,0.5); //透明度修改为0.5
})
</script>
</body>
f.自定义动画animate()
<style>
div{
position: fixed;
height: 200px;
width: 200px;
background-color: red;
}
</style>
<body>
<button>自定义动画</button>
<div>hello</div>
<script>
//自定义动画
$("button").click(function(){
$("div").animate({ //对象形式传递
left:400,
top:400
},500); //设置速度
})
</script>
</body>
(4)jQuery属性操作
a.设置和获取属性prop(),attr(),data()
- 1.固有属性
获取属性:prop("属性”)
设置属性:prop("属性”,“属性值”)
- 2.自定义属性
获取自定义属性:attr("属性")
设置自定义属性:attr("属性","属性值")
- 3.数据缓存data()
存放在内存中
获取自定义属性:data("属性")
设置自定义属性:data("属性","属性值")
全选案例
<body>
<input type="checkbox" class="all">全选
<input type="checkbox" class="box1">商品1
<input type="checkbox" class="box1">商品2
<input type="checkbox" class="box1">商品3
<input type="checkbox" class="box1">商品4
<script>
//1.全选框改变触发,全选框选中时每个商品框都选中
$(".all").change(function(){
var check = $(this).prop("checked") //获取全选框的属性值
$(".box1").prop("checked",check); //设置所以商品框的属性值
})
//2.商品框改变触发,每个商品框都选中时全选框选中
$(".box1").change(function(){
//用:checked获得选中的长度
if($(".box1:checked").length === $(".box1").length){
$(".all").prop("checked",true); //选中数量 === 总数量,全选框选中
}else{
$(".all").prop("checked",false); //选中数量!=总数量,全选框不选中
}
})
</script>
</body>
b.内容文本值
text()不会获取标签
购物车案例
<body>
<div class="list">
<div>
<input type="checkbox" class="all">全选
</div>
<div>
<input type="checkbox" class="box1" >商品1
<div class="price">单价:¥7</div>
<div class="count">
<a class="reduce">-</a>
<input type="text" value="1">
<a class="add">+</a>
</div>
<div class="totalPrice">总价:¥7</div>
</div>
<div>
<input type="checkbox" class="box1" >商品2
<div class="price">单价:¥11.11</div>
<div class="count">
<a class="reduce">-</a>
<input type="text" value="1">
<a class="add">+</a>
</div>
<div class="totalPrice">总价:¥11</div>
</div>
<div>
<input type="checkbox" class="box1">商品3
<div class="price">单价:¥12.10</div>
<div class="count">
<a class="reduce">-</a>
<input type="text" value="1">
<a class="add">+</a>
</div>
<div class="totalPrice">总价:¥12</div>
</div>
<div>
<input type="checkbox" class="box1">商品4
<div class="price">单价:¥8</div>
<div class="count">
<a class="reduce">-</a>
<input type="text" value="1">
<a class="add">+</a>
</div>
<div class="totalPrice">总价:¥8</div>
</div>
</div>
<script>
//1.全选框 //详细解读看上节
$(".all").change(function(){
var check = $(this).prop("checked")
$(".box1").prop("checked",check);
})
$(".box1").change(function(){
if($(".box1:checked").length === $(".box1").length){
$(".all").prop("checked",true);
}else{
$(".all").prop("checked",false);
}
})
//2.数量与价格
$(".add").click(function(){
var n = $(this).siblings("input").val();
n++;
$(this).siblings("input").val(n);//点击添加数量
//添加数量时,总价改变
var p =$(this).parent().siblings(".price").html().substr(4);//获取第4个字符后数字的内容
$(this).parent().siblings(".totalPrice").html("总价:¥"+(p*n).toFixed(2));//设置总价格
})
$(".reduce").click(function(){
var n = $(this).siblings("input").val();
n--;
if(n<1){n=1};
$(this).siblings("input").val(n);//点击减少数量
var p =$(this).parent().siblings(".price").html().substr(4);//获取第4个字符后数字的内容
$(this).parent().siblings(".totalPrice").html("总价:¥"+(p*n).toFixed(2));设置总价格
})
//3.input框修改时价格变化
$(".count").children("input").change(function(){
var n = $(this).val();
if(n<1){
n=1;
$(this).val(1);
};
var p =$(this).parent().siblings(".price").html().substr(4);
$(this).parent().siblings(".totalPrice").html("总价:¥"+(p*n).toFixed(2));
})
</script>
</body>
c.遍历对象each()方法
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<script>
var arr=["red","blue","pink"];
//each()遍历div
$("div").each(function(i,dom){
$(dom).css("color",arr[i]); //通过i修改元素
})
</script>
</body>
$.each({
name:"张三",
age:18
}, function(i,ele){
console.log(i); //name,age
console.log(ele);//张三,18
})
(5).jQuery操作元素(创建,添加,,删除)
- 1.创建元素
$("<li><li>")
- 2.内部添加
$("ul").append(li)
添加到最后面
$("ul").prepend(li)
添加到最前面
- 3.外部添加
$(".test").after(div)
添加到最后面
$(".test").before(div)
添加到最前面
- 4,删除元素
$("ul").remove()
$("ul").empty()
$("ul").html("")
(6)jQuery尺寸,位置操作
- 尺寸
- 位置
2.
D.jQuery事件
(1)注册事件
(2)事件处理on()
- 1.绑定多个事件
<div>hello</div>
<script>
//on绑定多个事件
$("div").on({
//1.鼠标经过,改变css
mouseover:function(){
$(this).css({
width:200+"px",
height:200+"px",
backgroundColor:"red"
});
},
//2.鼠标离开,改变css
mouseout:function(){
$(this).css("background","blue");
}
})
</script>
</body>
-
- on()的事件委派
- on()的事件委派
<body>
<ul>
<li>1</li>
<li>2</li>
</ul>
<script>
//效果等同于$("ul li").click();,click绑定在li
$("ul").on("click","li",function(){ //click绑定在ul
$(this).css("background","red");
})
</script>
</body>
- 3.动态元素的绑定事件
<body>
<ul>
<li>1</li>
<li>2</li>
</ul>
<script>
//普通注册事件,无法给 **未来** 创建的元素添加事件
$("ul li").mouseover(function(){
$(this).css("background","red");//3无法变色
})
//on注册事件
$("ul").on("mouseout","li",function(){
$(this).css("background","blue");//3变为蓝色
})
//动态创建元素
var li = $("<li>3</li>");
$("ul").append(li);
</script>
</body>
(3)解绑事件 off(),one()
<body>
<ul>
<li>1</li>
<li>2</li>
</ul>
<div>hello</div>
<script>
$("ul li").mouseover(function(){ //绑定在li
$(this).css("background","red");
})
$("ul").on("mouseout","li",function(){ //绑定在ul
$(this).css("background","blue");
})
//解绑事件
//$("ul").off(); //ul上事件被解绑,mouseout不变blue
$("li").off(); //li上的事件被解绑,mouseover不变red
$("ul").off("mouseout","li");//ul上事件被解绑,mouseout不变blue
$("div").one("click",function(){ //只执行一次
alert(1);
})
</script>
</body>
(4)自动触发事件
triggerHandler()不会触发默认事件
<body>
<div>say hello</div>
<input type="text">
<script>
// 1.
$("div").click(function(){
alert("hello");
})
$("div").click(); //触发点击事件
// 2.trigger与triggerHandler
$("input").focus(function(){
$(this).val("hello");
})
//$("input").trigger("focus"); //光标闪烁
$("input").triggerHandler("focus");//光标不闪,你不触发默认事件
</script>
</body>
###事件对象
<body>
<div>
say hello
</div>
<script>
$("div").on("click",function(e){
console.log("div");
e.stopPropagation(); //对象方法阻止冒泡,不再触发documen
})
$(document).on("click",function(){
console.log("elemnt");
})
</script>
</body>
(6)对象的拷贝exend()
var targetobj={
sex:"男"
msg:{
phone:119
}
};
var obj={
id:1,
name:"张三",
msg:{
age:18
}
};
//拷贝对象
$.extend(targetobj,obj);
console.log(targetobj);//id,name,msg{age},sex
//phone被覆盖
//浅拷贝
targetobj.msg.age = 20;
console.log(obj);//obj的age 也被改变,msg共用一个地址
- 深拷贝与浅拷贝
var targetobj={
sex:"男",
msg:{
phone:119
}
};
var obj={
id:1,
name:"张三",
msg:{
age:18
}
};
//深拷贝
$.extend(true,targetobj,obj);
console.log(targetobj);//id,name,msg{phone,age},sex
targetobj.msg.age=20;
console.log(obj);//obj的age为18
(7)多库共存
E.jQuery插件
- 懒加载
- 全屏滚动
- 组件