【八】JavaScript之函数
【1】函数
-
javascript 被称为披着面向对象的皮的函数式编程语言,是函数优先的编程语言,所以本质上js中的一切都是基于函数构建出来,所以函数本身也是对象,也是一等公民。
-
function,是类似变量一样的容器,代表了一段具有指定功能的代码段。
【2】函数使用的目的
- 一般情况,函数出现的目的为了提升代码的复用性和扩展性。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// for(var row=1,content; row<=4; row++){
// content = "";
// for(var star=1;star<=row*2-1;star++){
// content+="*";
// }
// console.log(content);
// }
//
// for(var row=1,content; row<=4; row++){
// content = "";
// for(var star=1;star<=row*2-1;star++){
// content+="*";
// }
// console.log(content);
// }
//
// for(var row=1,content; row<=4; row++){
// content = "";
// for(var star=1;star<=row*2-1;star++){
// content+="*";
// }
// console.log(content);
// }
//js中的普通函数声明写法
// function 函数名(形参列表){
// 函数体
// return 返回结果
// }
// js中的函数调用,被定义以后不调用是不会自动执行的。
// 函数名(实参列表);
function printStar() {
for(var row=1,content; row<=4; row++) {
content = "";
for(var star=1;star<=row*2-1;star++) {
content+="*";
}
console.log(content);
}
}
printStar();
printStar();
printStar();
</script>
</body>
</html>
【3】函数的声明
函数声明格式有3种:
// 1. 普通函数
function 函数名(形参1,形参2,形参3,....){
// 函数代表的代码段
}
// 2. 匿名函数
var 函数名 = function(形参1,形参2,形参3,....){
// 函数代表的代码段
}
// 3. 箭头函数[新版本的js里面出现的新型语法,是匿名函数的新写法]
var 函数名 = (形参1,形参2,形参3,....)=>{
// 函数代表的代码段
}
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
/**
* 普通函数
*/
// func(); // 普通函数可以先调用,后声明
// function func(){
// console.log("普通函数执行了")
// }
/**
* 匿名函数
*/
func = function(){
console.log("匿名函数执行了");
}
func(); // 匿名函数必须先赋值,后调用
/**
* 箭头函数[是匿名函数的新型写法,所以必须先赋值,后调用]
*/
func = ()=>{
console.log("箭头函数执行了")
}
func();
</script>
</body>
</html>
【4】立即执行的匿名函数
- 也叫匿名函数自执行。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// 匿名函数自执行
(function(name){
var num = 20; // 在函数中通过关键字var/let声明的变量,只能在当前函数中使用,无法被外界调用
console.log("匿名函数执行了。", `name=${name}`)
})("小明");
// 箭头函数自执行
((name)=>{
console.log("匿名函数执行了。", `name=${name}`)
console.log(num); // 此处报错
})("小红");
</script>
</body>
</html>
【5】函数的基本使用
// 在函数的使用中,如果希望函数中的功能变得更加强大,实用性和灵活性更强,可以给函数添加参数。通过参数,可以在函数调用时,来修改函数的使用情况。
function func1(num1,num2){
// console.log(num1+num2);
return num1+num2; // return 是函数内部想要往外部传递数据的关键字,这个关键字可以传递一个数据到外界
// 在return执行了以后,函数就结束了,所以不要在return后面写任何代码,没有作用。
}
// func1(1,2);
// 实参,就是实际在函数中使用的数据,形参就是形式上的参数,代表了实参在函数内部执行。我们可以理解为:在函数调用时,实参赋值给形参。
var ret = func1(100,50);
console.log(ret);
(1)内建函数
- build-in function,js内部提供的,我们可以直接调用的。
函数 | 描述 |
---|---|
parseInt() |
把数据转换成数值类型中的整数 |
parseFloat() |
把数据转换成数值类型的浮点数 |
isNaN() |
判断一个数据是否是非数字NaN |
alert(message) | 弹出一个警告框,message是提示内容 |
confirm(message) | 弹出一个确认框 |
prompt(message) | 弹出一个输入确认框 |
setInterval(func, ms) |
定时器[多次],定时执行指定代码段,func是一个匿名函数,ms表示定时间隔,单位:毫秒 |
clearInterval() |
删除指定的定时器 |
setTimeout(func, ms) |
定时器[一次],定时执行指定代码段 |
clearTimeout() |
删除指定的定时器 |
eval() |
内置语法解析器,把符合js语法规则的字符串当成代码执行,非常危险的函数。 |
encodeURI() | 对url地址中的内容进行编码处理,但不支持特殊符号的编码 |
decodeURI() | 对url地址中的内容进行解码处理,但不支持特殊符号的解码 |
encodeURIComponent() |
功能同上,但不具有上述缺点。 |
decodeURIComponent() |
功能同上,但不具有上述缺点。 |
close() | 关闭浏览器窗口,相当于window.close(),如果指定其他窗口对象的close方法,则关闭指定窗口。 |
open(url, target, windowname) | 新建一个浏览器窗口,返回值是新页面的window对象 |
btoa() | 使用base64编码对数据进行编码处理,把字符串内容编码成base64字符。 |
atob() | 使用base64编码对数据进行解码处理,把base64字符解码成字符串内容。 |
(2)模态框
- 基于浏览器提供的弹窗效果难看,而且样式单一并且功能不全
- 所以很多前端开发人员都会采用HTML+CSS+JS的方式重新实现自己的一套弹窗效果,这就是模态框。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
p{margin: 0; padding: 0;}
.messagebox{
width:100%;
height: 100%;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background: rgba(0, 0, 0,.3);
display: none;
}
.messagebox .warp{
width: 600px;
height: 350px;
background: #fff;
position: absolute; /* 子元素相对于父定位元素做绝对定位 */
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
border-radius: 10px;
box-shadow: 0 15px 30px 0 rgb(0,0,0);
}
.messagebox .btn{
width: 120px;
height: 42px;
line-height: 42px;
text-align: center;
color: #fff;
font-size: 16px;
background: #337ecc;
border: none;
outline: none;
border-radius: 4px;
cursor: pointer;
transition: all .3s linear;
}
.messagebox .btn:hover{
background: #409eff;
}
.messagebox .close{
width: 25px;
height: 25px;
display: block;
position: absolute;
top: 15px;
right: 15px;
cursor: pointer;
}
.messagebox .close svg{
max-width: 100%;
max-height: 100%;
transition: all .3s linear;
}
.messagebox .close:hover svg{
color: #409eff;
}
.messagebox .title{
height: 42px;
line-height: 42px;
font-size: 24px;
margin-top: 15px;
padding-left: 15px;
color: #333;
border-bottom: 1px solid rgba(0, 0, 0, .3);
}
.messagebox .message{
margin: 15px;
max-height: 180px;
overflow: auto;
}
.messagebox .footer{
position: absolute;
right: 25px;
bottom: 25px;
}
</style>
</head>
<body>
<button class="login-btn">登录</button>
<div class="messagebox">
<div class="warp">
<span class="close">
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
<path fill="currentColor" d="M764.288 214.592 512 466.88 259.712 214.592a31.936 31.936 0 0 0-45.12 45.12L466.752 512 214.528 764.224a31.936 31.936 0 1 0 45.12 45.184L512 557.184l252.288 252.288a31.936 31.936 0 0 0 45.12-45.12L557.12 512.064l252.288-252.352a31.936 31.936 0 1 0-45.12-45.184z"></path>
</svg>
</span>
<p class="title">弹窗标题</p>
<div class="message">
弹窗的内容弹窗的内容弹窗的内容弹窗的内容弹窗的内容弹
</div>
<div class="footer">
<button class="btn confirm">确定</button>
<button class="btn cancel">取消</button>
</div>
</div>
</div>
<script>
var btn = document.querySelector(".login-btn");
var confirmbtn = document.querySelector(".messagebox .confirm");
var cancelbtn = document.querySelector(".messagebox .cancel");
var closebtn = document.querySelector(".messagebox .close");
var messagebox = document.querySelector(".messagebox")
btn.onclick = function(){
messagebox.style.display = "block";
}
confirmbtn.onclick = function(){
alert("您点击了确定")
}
cancelbtn.onclick = function(){
messagebox.style.display = "none";
}
closebtn.onclick = function(){
messagebox.style.display = "none";
}
</script>
</body>
</html>
(3)定时器的基本使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button class="btn">停止刷新页面</button>
<button class="btn start">开始刷新页面</button>
<hr>
<h1 class="h1">0</h1>
<script>
/**
* setInterval(匿名函数,间隔时间) 定时多次,异步执行,不会产生阻塞
* 返回值是序数,表示当前定时器是当前页面的第几个定时器,用于清除当前定时器
*/
// setInterval(()=>{
// console.log(new Date().getTime());
// }, 1000); // 1s = 1000ms
/**
* clearInterval(序数) 清除指定定时器
*/
// var num = 1;
// var timer = setInterval(()=>{
// console.log(num++);
// if(num>=5){
// // 如果不清除定时器,除非页面刷新,否则定时器是不会停止
// console.log(timer, typeof timer);
// clearInterval(timer);
// }
// }, 1000);
/**
* setTimeout(匿名函数, 时间间隔) 定时一次,异步执行,不会产生阻塞
* 返回值是序数,表示当前定时器是当前页面的第几个定时器,用于清除当前定时器
*/
// setTimeout(()=>{
// // 倒计时3秒,页面跳转到地址url地址
// location.href="https://www.baidu.com"
// }, 3000);
/**
* clearTimeout(序数) 清除指定定时器
*/
/* function start_timer(){
var t = setTimeout(()=>{
location.reload() // F5,刷新当前页面
}, 2000);
var btn = document.querySelector(".btn");
btn.onclick = ()=>{
clearTimeout(t);
}
var start = document.querySelector(".start");
start.onclick = ()=>{
start_timer();
}
}
start_timer();*/
/**
* 因为定时器是并发执行的,所以要尽量保证,同一个定时器在同一个页面中唯一。
*/
// var h1 = document.querySelector(".h1");
// var t2 = null;
// h1.onclick = ()=>{
// clearInterval(t2); // 每次创建一个新的定时器之前,把旧的定时器移除。
// t2 = setInterval(()=>{
// h1.innerHTML= parseInt(h1.innerHTML) + 1;
// },1000);
// }
/**
* 绝对时间间隔的定时器实现
*/
// var num = 1;
// setInterval(()=>{
// alert(num); // 阻塞代码并不会延迟定时器 setInterval 的计时功能。
// num++;
// },2000);
// 我们希望实现的效果时,阻塞的代码也能把定时器也停滞下来。
// 改成setTimeout来实现定时多次,就可以解决这个问题
var num = 1;
function timer(){
alert(num++);
setTimeout(()=>{
timer(); // 实现定时多次
},2000);
}
timer();
</script>
</body>
</html>
(4)定时器的实际应用
- 开发者,我们基于定时器结合js操作css样式或者html代码,就可以实现各种的酷炫的动态交互效果了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
width: 150px;
height: 150px;
background: red;
}
.box2{
position: absolute;
}
</style>
</head>
<body>
<!-- <div class="box1"></div>-->
<!-- <script>-->
<!-- document.querySelector(".box1").onclick = function(){-->
<!-- console.log(this); // 在方法中,可以通过this获取当前对象-->
<!-- var num = 0;-->
<!-- // 使用定时器集合css样式实现动画的核心就是让整个过程中涉及到的数值在定时器中进行计算-->
<!-- setInterval(()=>{-->
<!-- this.style.borderRadius = `${num++}px`;-->
<!-- }, 24);-->
<!-- }-->
<!-- </script>-->
<!-- <div class="box2"></div>-->
<!-- <script>-->
<!-- var box2 = document.querySelector(".box2")-->
<!-- box2.style.left = 0;-->
<!-- var num = 1;-->
<!-- var t;-->
<!-- box2.onclick = ()=>{-->
<!-- clearInterval(t);-->
<!-- t = setInterval(()=>{-->
<!-- num *= 1.1; // 实现先慢后块(ease-in)-->
<!-- console.log(num);-->
<!-- box2.style.left = `${num}px`;-->
<!-- if(num>=1200){-->
<!-- clearInterval(t);-->
<!-- }-->
<!-- }, 24);-->
<!-- }-->
<!-- </script>-->
<div class="box3"></div>
<script>
var box3 = document.querySelector(".box3");
box3.style.opacity = 1; // 设置不透明
var t;
box3.onclick = ()=>{
clearInterval(t);
t = setInterval(()=>{
box3.style.opacity-=0.01;
if(box3.style.opacity < 0){
box3.style.display = "none";
clearInterval(t);
}
},24);
}
</script>
<div></div>
</body>
</html>
(5)模态框添加动画效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
p{margin: 0; padding: 0;}
.messagebox{
width:100%;
height: 100%;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background: rgba(0, 0, 0,.3);
display: none;
}
.messagebox .warp{
width: 600px;
height: 350px;
background: #fff;
position: absolute; /* 子元素相对于父定位元素做绝对定位 */
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
border-radius: 10px;
box-shadow: 0 15px 30px 0 rgb(0,0,0);
display: none;
}
.messagebox .btn{
width: 120px;
height: 42px;
line-height: 42px;
text-align: center;
color: #fff;
font-size: 16px;
background: #337ecc;
border: none;
outline: none;
border-radius: 4px;
cursor: pointer;
transition: all .3s linear;
}
.messagebox .btn:hover{
background: #409eff;
}
.messagebox .close{
width: 25px;
height: 25px;
display: block;
position: absolute;
top: 15px;
right: 15px;
cursor: pointer;
}
.messagebox .close svg{
max-width: 100%;
max-height: 100%;
transition: all .3s linear;
}
.messagebox .close:hover svg{
color: #409eff;
}
.messagebox .title{
height: 42px;
line-height: 42px;
font-size: 24px;
margin-top: 15px;
padding-left: 15px;
color: #333;
border-bottom: 1px solid rgba(0, 0, 0, .3);
}
.messagebox .message{
margin: 15px;
max-height: 180px;
overflow: auto;
}
.messagebox .footer{
position: absolute;
right: 25px;
bottom: 25px;
}
</style>
</head>
<body>
<button class="login-btn">登录</button>
<div class="messagebox">
<div class="warp">
<span class="close">
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
<path fill="currentColor" d="M764.288 214.592 512 466.88 259.712 214.592a31.936 31.936 0 0 0-45.12 45.12L466.752 512 214.528 764.224a31.936 31.936 0 1 0 45.12 45.184L512 557.184l252.288 252.288a31.936 31.936 0 0 0 45.12-45.12L557.12 512.064l252.288-252.352a31.936 31.936 0 1 0-45.12-45.184z"></path>
</svg>
</span>
<p class="title">弹窗标题</p>
<div class="message">
弹窗的内容弹窗的内容弹窗的内容弹窗的内容弹窗的内容弹
</div>
<div class="footer">
<button class="btn confirm">确定</button>
<button class="btn cancel">取消</button>
</div>
</div>
</div>
<script>
var btn = document.querySelector(".login-btn");
var confirmbtn = document.querySelector(".messagebox .confirm");
var cancelbtn = document.querySelector(".messagebox .cancel");
var closebtn = document.querySelector(".messagebox .close");
var messagebox = document.querySelector(".messagebox");
var warp = document.querySelector(".messagebox .warp");
var bg_timer;
confirmbtn.onclick = function(){
alert("您点击了确定");
}
btn.onclick = show // 此处,只是赋值函数而已,真正要执行的函数的时候,是在用户点击时,所以show不能加上小括号
cancelbtn.onclick = hide
closebtn.onclick = hide
function show(){
// 显示窗口
let opacity = 0;
messagebox.style.opacity = opacity;
messagebox.style.display = "block";
// 定时器,显示背景
clearInterval(bg_timer);
bg_timer = setInterval(()=>{
opacity+=0.1;
messagebox.style.opacity = opacity;
if(opacity>=1){
clearInterval(bg_timer);
}
},24);
warp.style.display = "block";
}
function hide(){
// 隐藏窗口
let opacity = 1;
// 定时器,显示背景
clearInterval(bg_timer);
bg_timer = setInterval(()=>{
opacity-=0.1;
messagebox.style.opacity = opacity;
if(opacity<=0){
clearInterval(bg_timer);
messagebox.style.display = "none";
warp.style.display = "none";
}
},24);
}
</script>
</body>
</html>
(6)eval内置解释器函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<textarea name="code" cols="30" rows="10"></textarea>
<br>
<button>运行</button>
<script>
var code = document.querySelector('textarea[name="code"]')
var btn = document.querySelector('button')
btn.onclick = ()=>{
try {
eval(code.value);
}catch (e) {
console.log(e.message);
}
}
</script>
</body>
</html>
(7)URL地址栏参数的编码处理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// content = "内置函数+/"
// // 编码
// url_content = encodeURI(content)
// console.log(url_content)
// // 解码
// result = decodeURI(url_content)
// console.log(result)
// 上面的encodeURI与decodeURI仅仅能对普通内容进行编码转换,但是不能对特殊符号进行内容转换。
content = btoa("+=")
url_content = encodeURIComponent(content)
console.log(url_content)
// 解码
result = decodeURIComponent(url_content)
console.log(result)
</script>
</body>
</html>
(8)打开与关闭窗口
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button class="closecurrent">关闭当前页面</button>
<br>
<input type="text" name="baidu"><button class="search">搜索</button><button class="closepage">关闭页面</button>
<script>
var baidu = document.querySelector('input[name="baidu"]')
var search = document.querySelector('.search')
var closepage = document.querySelector('.closepage')
var closecurrent = document.querySelector('.closecurrent')
var w;
search.onclick = ()=>{
console.log(baidu.value);
// 替换当前窗口url,访问对应页面
// location.href=`https://www.baidu.com/s?wd=${baidu.value}`
// 新建窗口再打开url地址
w = open(`https://www.baidu.com/s?wd=${baidu.value}`, '_blank')
// open(`https://www.baidu.com/s?wd=${baidu.value}`, '_self')
// open(`https://www.baidu.com/s?wd=${baidu.value}`, '_top')
}
/**
* open(url=URL地址,target=打开方式, windowname=窗口名称)
* URL地址,新页面的地址
* 打开方式,就是a标签的target属性值
* _self 在当前页面窗口中打开url地址
* _blank 在新建浏览器标签页中打开url地址
* _top 在顶级页面窗口中打开url地址
* 窗口名称,就是新开浏览器窗口,绑定该窗口为指定名称,绑定后续所有的浏览器操作
*
* 返回值就是新页面的window对象
*/
closepage.onclick = ()=>{
// w就是上面open打开的浏览器页面的窗口对象,通过窗口对象就可以关闭指定窗口
w.close()
}
closecurrent.onclick = ()=>{
close(); // 相当于 window.close(),默认情况下window代表的就是当前页面窗口对象
}
</script>
</body>
</html>
(9)base64编码处理函数
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
// base64是一个网络数据传输的数据转码函数,主要目的是为了避免在网络数据传输过程中,二进制数据与多字节数据的丢失。
// python中也有内置模块base64模块提供了 base64.b64encode()、base64.b64decode()
data = '{"name": "xiaoming","age": 17}'
content = btoa(data) // base64编码函数
// console.log(content) // "eyJuYW1lIjogInhpYW9taW5nIiwiYWdlIjogMTd9"
// content = "eyJuYW1lIjogInhpYW9taW5nIiwiYWdlIjogMTd9"
// data = atob(content) // 解码函数
// console.log(data) // {"name": "xiaoming","age": 17}
// // base64不是加密,而是一种编码处理而已。
</script>
</body>
</html>
标签:messagebox,定时器,函数,JavaScript,querySelector,var,document
From: https://www.cnblogs.com/dream-ze/p/17525625.html