网页ppt
const sectionsCount = $("section").length;
let activeIndex = 0;
// 监听用户按下空格和方向键的事件
$(document).on("keydown", (e) => {
e.preventDefault();
if (e.key === " " || e.key === "ArrowRight") {
goRight();
}
if (e.key === "ArrowLeft") {
goLeft();
}
});
// 监听按钮点击事件
$(".btn.left").click(goLeft);
$(".btn.right").click(goRight);
// 切换下一张的函数
function goLeft() {
var list=document.querySelectorAll('section');
for(i=1;i<list.length;i++)
list[activeIndex].style.display="none";
if (activeIndex === 4) {
$(".btn.right").removeClass('disable')
}
if (activeIndex === 0) {
return;
}
if (activeIndex === 1) {
$(".btn.left").addClass('disable',true)
}
activeIndex -= 1;
switchPage();
}
// 切换上一张的函数
function goRight() {
var list=document.querySelectorAll('section');
for(i=1;i<list.length;i++)
list[activeIndex].style.display="none";
if (activeIndex === sectionsCount - 1) {
return;
}
$(".btn.left").removeClass('disable')
activeIndex += 1;
if(activeIndex==4){
$(".btn.right").addClass('disable',true)
}
switchPage();
}
function switchPage() {
// TODO: 请补充该函数,实现根据activeIndex切换页面的功能,并且在到达最后一页或第一页时给相应的按钮添加disable类
var list=document.querySelectorAll('section');
// console.log(list)
// console.log(activeIndex)
list[activeIndex].style.display="block";
$(".page").html(activeIndex+1+"/"+5);
}
西游记之西天取经
body {
background: url(../images/background.webp) no-repeat;
background-size: cover;
overflow-y: hidden;
}
.playground {
width: 800px;
margin: 400px auto;
overflow: hidden;
}
.actor {
float: left;
}
.actor:first-child {
width: 200px;
height: 180px;
background: url(../images/west_01.png) no-repeat;
/* TODO 填空 */
animation: a1 0.8s steps(8) infinite;
}
.actor:nth-child(2) {
width: 200px;
height: 180px;
background: url(../images/west_02.png) no-repeat;
/* TODO 填空 */
animation: a2 0.8s steps(8) infinite;
}
.actor:nth-child(3) {
width: 170px;
height: 240px;
background: url(../images/west_03.png) no-repeat;
/* TODO 填空 */
animation: a3 0.8s steps(8) infinite;
}
.actor:last-child {
width: 210px;
height: 200px;
background: url(../images/west_04.png) no-repeat;
/* TODO 填空 */
animation: a4 0.8s steps(8) infinite;
}
@keyframes a1{
from{
background-position-x: 0;
}
to{
background-position-x: -1600px;
}
}
@keyframes a2{
from{
background-position-x: 0;
}
to{
background-position-x: -1600px;
}
}
@keyframes a3{
from{
background-position-x: 0;
}
to{
background-position-x: -1360px;
}
}
@keyframes a4{
from{
background-position-x: 0;
}
to{
background-position-x: -1680px;
}
}
商品销量和销售额实时展示看板
// 指定图表的配置项和数据
const charData = {
title: {
text: '云课课程销量和销售额看板',
width: 100,
height: 50,
textStyle: {
lineHeight: 50,
},
left: 'center',
},
grid: {
top: 80,
},
tooltip:{
show: true,
},
xAxis: {
data: [],
},
// TODO:补全 `yAxis` 的设置,要求“销售额”(即,配置项 `name`)的位置(即,配置项 `position`)在图表的左侧,“销量”(即,配置项 `name`)的位置(即,配置项 `position`)在图表的右侧。
yAxis: [{
type: 'value',
name: '销售额',
position: 'left',
},
{
type: 'value',
name: '金额',
position: 'right',
}],
series: [
{
name: '销售额',
type: 'line',
data: [],
yAxisIndex: 0,
smooth: true
},
{
name: '销量',
type: 'bar',
data: [],
yAxisIndex: 1,
smooth: true
}
]
};
// 以下代码为模拟后端服务器返回数据
let sale = 0;
let count = 0;
// 销售额
const saleObj = {};
// 销量
const countObj = {};
let index = 0;
function Ajax() {
return new Promise((resolve, reject) => {
let randomNum = Math.random();
const randomSum = () => (randomNum * 500 + 900);
const randomCount = () => (randomNum * 50 + 80);
let i = index++ * 10
let key = `10:${i == 0 ? "00" : i}`;
if (index < 7) {
sale = randomSum();
Object.assign(saleObj, { [key]: sale.toFixed(2) })
count = randomCount();
Object.assign(countObj, { [key]: count.toFixed(2) })
}
const respondBody = {
"code": 200,
"msg": "success",
"data": {
saleObj,
countObj
}
};
setTimeout(() => {
resolve(respondBody);
}, 1000)
})
}
async function renderChart() {
const result = await Ajax();
document.querySelector("#result").innerText = JSON.stringify(result);
const myChart = echarts.init(document.getElementById('main'));
// TODO:补全代码,正确给 X 轴的时间,以及 Y 轴的商品的销售额 saleObj 和销量赋值 countObj。
console.log( Object.values(saleObj))
charData.series[0].data=Object.values(saleObj)
charData.series[1].data=Object.values(countObj)
charData.xAxis.data= (Object.keys(saleObj))
console.log( charData.xAxis,"chartdata")
myChart.setOption(charData, true);
document.querySelector("#data").innerText = JSON.stringify(charData);
}
renderChart();
let times = 0;
let timer = setInterval(() => {
renderChart();
++times == 6 && clearInterval(timer);
}, 2000)
校园一卡通
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>蓝桥校园一卡通</title>
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/index.css" />
</head>
<body>
<div id="app">
<div class="form">
<div class="card" id="cardStyle">
<div class="cardName">蓝桥校园一卡通</div>
<div class="info">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
<div class="content">
<div class="form-group">
<label for="studentName">姓名</label>
<input type="text" class="form-control" id="studentName" placeholder="请输入姓名"
aria-describedby="inputSuccess2Status">
<span id="vail_name" style="display: none;" class="help-block"> 姓名是2-4个汉字,请您检查输入的内容</span>
</div>
<div class="form-group">
<label for="studentId">学号</label>
<input type="number" class="form-control" id="studentId" placeholder="请输入学号">
<span id="vail_studentId" style="display: none;" class="help-block"> 学号是1-12位的数字,请您检查输入的内容</span>
</div>
<div class="form-group">
<label for="college">学院</label>
<select id="college" class="form-control">
<option value="软件工程学院">软件工程学院</option>
<option value="信息技术学院">信息技术学院</option>
<option value="数字媒体学院">数字媒体学院</option>
<option value="计算机科学学院">计算机科学学院</option>
</select>
</div>
<button id="submit">制卡</button>
</div>
</div>
</div>
<script>
// 获取DOM元素对象
const studentName = document.getElementById("studentName"); // 姓名
const formgroup = document.getElementsByClassName("form-group"); // 姓名
const studentId = document.getElementById("studentId"); // 学号
const college = document.getElementById("college"); // 学院
const submit = document.getElementById("submit"); // 制卡按钮
const cardStyle = document.getElementById("cardStyle"); // 卡片
const item = document.querySelectorAll(".item") // 卡片项
submit.onclick = () => {
document.getElementById('vail_name').style.display = 'block'
// console.log(item.length)
// TODO 待补充代码
var nameReg = /^[\u4e00-\u9fa5]{2,4}$/; // 2-4位的汉字名字
console.log(studentName.value)
var naR = nameReg.test(studentName.value)
console.log(naR)
var numberReg = /^\d{1,12}$/; // 2-4位的汉字名字
var nR = numberReg.test(studentId.value);
console.log(nR)
if (!naR) {
formgroup[0].classList.add("has-error")
document.getElementById('vail_name').style.display = 'block'
}
if (!nR) {
formgroup[1].classList.add("has-error")
document.getElementById('vail_studentId').style.display = 'block'
}
if (naR && nR) {
item[0].innerHTML = "姓名:" + studentName.value
item[1].innerHTML = "学号:" + studentId.value
item[2].innerHTML = "学院:" + college.value
// 添加 showCard 类显示放大一卡通的动画,请勿删除
cardStyle.classList.add('showCard')
}
}
</script>
</body>
</html>
心愿便利贴
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>心愿便利贴</title>
<!-- 引入element-ui样式 -->
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="./css/wish.css">
<!-- 引入element-ui组件库 -->
<script src="./js/vue.min.js"></script>
<script src="./js/index.js"></script>
</head>
<body>
<div id="app">
<h1>心愿便利贴</h1>
<div class="container">
<!-- TODO 待修改的代码 -->
<div class="card" :class="item.css" v-for="(item,index) in wishList" :key="index">
<div class="header">
<img class="close" @click="closeCard(index)" src="./images/ding.png" alt="close">
</div>
<el-image
v-if="item.pic"
style="width: 100px; height: 100px"
:src="item.pic"
:preview-src-list="picList">
</el-image>
<div class="content">
{{item.content}}
</div>
<div class="name">{{item.name}}</div>
</div>
</div>
<div class="form">
<el-form ref="form" :rules="rules" label-position="left" :model="form" label-width="80px">
<el-form-item label="姓名" prop="name">
<el-input id="firstName" v-model="form.name" placeholder="请输入姓名"></el-input>
</el-form-item>
<el-form-item label="许愿内容" prop="content">
<el-input type="textarea" id="content" placeholder="请输入内容" v-model="form.content" show-word-limit></el-input>
</el-form-item>
<el-form-item label="图片上传">
<el-upload
ref="uploadRef"
action="#"
:limit="1"
list-type="picture-card"
:on-remove="handleRemove"
:on-change="getPic"
:auto-upload="false">
<i slot="default" class="el-icon-plus"></i>
<div slot="file" slot-scope="{file}">
<img
class="el-upload-list__item-thumbnail"
:src="file.url"
>
<span class="el-upload-list__item-actions">
<span
class="el-upload-list__item-preview"
@click="handlePictureCardPreview(file)"
>
<i class="el-icon-zoom-in"></i>
</span>
<span
v-if="!disabled"
class="el-upload-list__item-delete"
@click="handleRemove(file)">
<i class="el-icon-delete"></i>
</span>
</span>
</div>
</el-upload>
</el-form-item>
<el-form-item>
<el-button id="onSubmit" type="primary" @click="onSubmit">发布</el-button>
<el-button @click="onRest">重置</el-button>
</el-form-item>
</el-form>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="form.pic" alt="">
</el-dialog>
</div>
</div>
</body>
<script>
const app = new Vue({
el: "#app",
data: {
wishList: [],
form: {
name:'',
content: '',
pic: ''
},
rules: {
// TODO 待补充验证的代码
name: [
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 2, max: 4, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
content: [
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 1, max: 30, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
},
num:1,
picList: [],
textarea: '',
dialogVisible: false,
disabled: false
},
methods: {
// 提交方法
onSubmit() {
this.$refs['form'].validate((valid) => {
if (valid) {
let obj = this.form;
obj.css = 'item' + this.num;
this.num++;
if(this.num > 4) {
this.num = 1;
}
this.wishList.push(obj)
this.form = {};
this.$refs.uploadRef.uploadFiles.pop()
console.log(this.wishList);
} else {
this.$message({
message: '提交错误!请检查输入内容',
type: 'warning'
});
return false;
}
});
},
// 关闭许愿卡
closeCard(index) {
this.wishList.splice(index,1)
},
// 重置表单
onRest() {
this.$refs['form'].resetFields();
},
// 图片删除
handleRemove(file) {
let index = this.$refs.uploadRef.uploadFiles.findIndex(e => e.uid === file.uid);
this.$refs.uploadRef.uploadFiles.splice(index,1);
},
// 模拟上传图片
getPic(e) {
this.form.pic = e.url;
this.picList.push(e.url)
},
// 预览图片
handlePictureCardPreview(file, fileList) {
this.form.pic = file.url;
this.dialogVisible = true;
}
}
});
</script>
</html>
消失的Token
<!DOCTYPE html>
<html lang="zn-CH">
<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">
<script src="./lib/vue.min.js"></script>
<script src="./lib/vuex.min.js"></script>
<script src="./store/BaseModule.js"></script>
<script src="./store/UserModule.js"></script>
<script src="./store/index.js"></script>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<div id="app">
<div class="wrapper" style="width: 900px;">
<!-- 2. 登录成功后的欢迎界面 -->
<Panel v-if="token" :username="username">
{{welcome}}
</Panel>
<!-- 1. 登录界面 -->
<Login v-else @confirm="login">
{{welcome}}
</Login>
</div>
</div>
<script src="./components/login.js"></script>
<script src="./components/panel.js"></script>
<script>
// TODO 修改下面错误代码
var app = new Vue({
el: '#app',
data() { },
computed: {
welcome() {
return store.getters.welcome
},
username() {
return store.getters['user/username']
},
token() {
return store.getters['user/token']
}
},
methods: {
// 回车/点击确认的回调事件
login(username) {
username && store.commit('user/login', { username, token: 'sxgWKnLADfS8hUxbiMWyb' })
username && store.commit('say', '登录成功,欢迎你回来!')
}
}
})
</script>
</body>
</html>
封装promise
const fs = require('fs')
const path = require('path')
const textPath = path.join(__dirname, '/test.md')
// 读取示例文件
fs.readFile(textPath, 'utf8', (err, contrast) => {
// 通过promisefy转化为链式调用
const readFileSync = promisefy(fs.readFile)
// console.log(JSON.stringify(readFileSync) )
readFileSync(textPath, 'utf8')
.then((res) => {
console.log(res === contrast) // 此处结果预期:true,即promise返回内容与前面读取内容一致
})
.catch((err) => {})
})
const promisefy = (fn) => {
// TODO 此处完成该函数的封装
return function(path,type){
return new Promise((resolve,reject)=>{
fn(path,type,(err,res)=>{
if(err){
console.log(err)
reject(err)
}
console.log(res)
resolve(res)
})
})
}
}
module.exports = promisefy // 请勿删除该行代码
购物车
//模拟赛三拖拽问题
<!-- TODO: 补充拖拽事件,请不要改动任何 id 属性 -->
<template>
<div class="container">
<div class="good-list">
<div draggable="true" @dragstart="drag($event,good)" v-for="good in goods" :key="good.name" class="good">
<img :src="good.cover" />
<span>{{ good.name }}</span>
<span>¥{{ good.price }}</span>
</div>
</div>
<div id="trolley" @dragover.prevent @drop="dragend($event)" class="trolley">
<span id="bought" class="bought" v-if="bought.length !== 0">{{
bought.length
}}</span>
<img src="./images/trolley.jpeg" />
</div>
<div class="result">
<div>
购物车商品:<span id="goods">{{ goodsDetail }}</span>
</div>
<div>
购物车商品总计:<span id="total">{{ totalPrice }}</span>
</div>
</div>
</div>
</template>
module.exports = {
data() {
return {
goods: [
{
name: "畅销书",
price: 30,
cover: "./images/book.jpeg",
},
{
name: "收纳箱",
price: 60,
cover: "./images/box.jpeg",
},
{
name: "纸巾",
price: 20,
cover: "./images/paper.jpeg",
},
{
name: "电视",
price: 1000,
cover: "./images/tv.jpg",
},
],
bought: [],
};
},
// TODO: 请补充实现代码
computed: {
totalPrice() {
console.log(this.bought);
let sum=0
for(let i=0;i<this.bought.length;i++){
sum+=Number(this.bought[i].price)
}
return sum;
},
goodsDetail() {
let obj={
'畅销书':0,
'收纳箱':0,
'纸巾':0,
'电视':0
}
for(let it of this.bought){
if(it.name=='畅销书')obj['畅销书']++
if(it.name=='收纳箱')obj['收纳箱']++
if(it.name=='纸巾')obj['纸巾']++
if(it.name=='电视')obj['电视']++
}
let str=''
for(let it in obj){
if(obj[it]>0){
str+=`${it}*${obj[it]} `
}
}
return str;
},
},
methods: {
drag(ev,good){
ev.dataTransfer.setData("name", good.name);
ev.dataTransfer.setData("price", good.price);
},
dragend(ev){
const name = ev.dataTransfer.getData("name");
const price = ev.dataTransfer.getData("price");
let obj={
name,
price
}
this.bought.push(obj)
}
}
};
分页
/**
* @description 得到分页数组 indexArr,如[1,2,3,4,10],[1,3,4,5,10],[1,7,8,9,10]
* @param {number} currentPage 当前页数,默认为第一页
* @param {number} totalPages 总的页码数
* @param {number} pagerCount 设置最大页码按钮数。 页码按钮的数量,当总页数超过该值时会折叠
* @return {Array} 分页数组 indexArr
*/
const createPaginationIndexArr = (currentPage, totalPages, pagerCount) => {
let indexArr = [];
// TODO:根据传参生成分页数组 indexArr
// console.log(currentPage, totalPages, pagerCount);//1,10,5
if(totalPages<=pagerCount){
for(let i=1;i<=totalPages;i++){
indexArr.push(i)
}
}
if(totalPages>pagerCount){
indexArr.push(1)
if(currentPage<=pagerCount-2){
for(let i=2;i<pagerCount;i++){
indexArr.push(i)
}
}else if(currentPage>totalPages-pagerCount+2){
for(let i=totalPages-(pagerCount-2);i<=totalPages-1;i++){
indexArr.push(i)
}
}else{
for(let i=currentPage+1-(pagerCount-2)+1;i<=currentPage+1;i++){
indexArr.push(i)
}
}
indexArr.push(totalPages)
}
console.log(indexArr);
return indexArr;
}
module.exports = {
createPaginationIndexArr
}
/**
* @description ajax 请求,通过传递的 currentPage, pageSize 获取到当前页和总页数的数据
* @param {string} url 请求地址,必填
* @param {string} method 请求方式,可选参数,默认为 get
* @param {string} data 请求体数据,可选参数
* @param {number} currentPage 当前页数,必填
* @param {number} pageSize 每页显示条目个数,必填
* @return {object} {data,total} data为data.json中data数组的部分数据,total为data.json中total的值
* */
async function ajax({ url, method = "get", data, query: { currentPage, pageSize } }) {
// TODO:根据函数参数 `query` 对象 `currentPage, pageSize` 获得当前页的数据
let result = {
data:[],
total:0
}
await axios({
methods:method,
url,
data,
/* params:{
currentPage, pageSize
} */
}).then(res=>{
console.log(res.data);
let arr=[]
for(let i=(currentPage-1)*10;i<pageSize+(currentPage-1)*10;i++){
arr.push(res.data.data[i])
}
result.data=arr
result.total=res.data.total
},
err=>{
console.log(err.message);
})
// console.log(result);//
return result;
}
class Pagination {
/**
* @param {Element} root
* @param {number} pageSize 每页显示条目个数
* @param {number} total 总条目数
* @param {number} pagerCount 设置最大页码按钮数。 页码按钮的数量,当总页数超过该值时会折叠
* @param {number} currentPage 当前页数,默认为第一页
* @param {function} currentChange current-page 改变时触发
*/
constructor(root, { pageSize, total, pagerCount, currentPage }, { currentChange }) {
if (pagerCount % 2 == 0) {
pagerCount--;
}
this.root = root;
this.pageSize = pageSize || 10;
this.total = total;
this.pagerCount = pagerCount || 7;
this.currentPage = currentPage || 1;
this.currentChange = currentChange;
this.totalPages = Math.ceil(total / pageSize);
this.initPagination();
}
/**
* @description 初始化分页组件,首次创建和 this.currentPage 改变时调用
* */
initPagination() {
const indexArr = createPaginationIndexArr(this.currentPage, this.totalPages, this.pagerCount);
document.querySelector("#index-arr").innerText = JSON.stringify(indexArr);
this.renderPagination(indexArr);
this.initEvents();
this.currentChange(this.currentPage);
}
/**
* @description 根据序号数组生成分页组件的字符串模板通过 innerHTML 挂载在 root 元素内
* @param {Array} indexArr 分页数组 indexArr
* @return {String} 分页组件的字符串模板
*/
renderPagination(indexArr) {
let template = '';
// TODO:根据 indexArr 数组生成分页组件的字符串模板 template
// console.log(indexArr);
let arr=[]
arr.push(indexArr[0])
for(let i=1;i<this.pagerCount-1;i++){
if(indexArr[i-1]!==indexArr[i]-1){
arr.push('...')
arr.push(indexArr[i])
}
else if(indexArr[this.pagerCount-1]!==indexArr[this.pagerCount-2]+1&&i===this.pagerCount-2){
arr.push(indexArr[i])
arr.push('...')
}
else arr.push(indexArr[i])
}
arr.push(indexArr[indexArr.length-1])
console.log(arr);
console.log(this.currentPage);
for(let i=0;i<arr.length;i++){
if(this.currentPage===arr[i]){
template+= `<li class="number active">${arr[i]}</li>`
// console.log('a');
}
else if(arr[i]==='...'){
template+=`<li class="number more">...</li>`
// console.log('b');
}
else{
template+=`<li class="number ">${arr[i]}</li>`
// console.log('c');
}
}
this.root.innerHTML = `
<div class="pagination">
<div class="btn btn-left" id="btn-prev"><</div>
<ul class="pager">${template} </ul>
<div class="btn btn-right" id="btn-next">></div>
</div>`;
}
/**
* @description 事件绑定,改变 this.currentPage 的值,值在 1 到 this.totalPages 之间
**/
initEvents() {
this.root.querySelector("#btn-prev").addEventListener('click', () => {
// TODO:"<" 按钮的点击事件, 点击时 this.currentPage - 1
console.log('iii');
if(this.currentPage>1){
this.currentPage--
this.initPagination();
}
})
this.root.querySelector("#btn-next").addEventListener('click', () => {
// TODO:">" 按钮的点击事件, 点击时 this.currentPage + 1
if(this.currentPage<this.totalPages){
this.currentPage++
console.log(this.currentPage);
this.initPagination();
}
})
this.root.querySelector(".pager").addEventListener('click', (e) => {
if (e.target.nodeName.toLowerCase() === 'li') {
if (this.currentPage === e.target.innerText) return;
if (e.target.classList.contains('more')) return;
this.currentPage = Number(e.target.innerText)
}
this.initPagination();
});
}
}
const paginationConfigObj = { pageSize: 10, total: 100, pagerCount: 5 };
const root = document.querySelector(".pagination-container");
async function renderContent(currentPage) {
document.querySelector("#current-page").innerText = currentPage;
const { data, total } = await ajax({ url: "./js/data.json", method: "get", query: { currentPage, ...paginationConfigObj } });
document.querySelector("#ajax-data").innerText = JSON.stringify(data);
document.querySelector("#ajax-total").innerText = JSON.stringify(total);
const contentEle = document.querySelector('.content');
let template = data.reduce((prev, cur) =>
prev + `
<li class="item" data-index="${cur.id}">
<h4 class="title">${cur.title}</h4>
<div class="item-right">
评论数:<span class="replay-count">${cur.replayCount}</span>
/
点击数:<span class="click-count">${cur.clickCount}</span>
</div>
</li>`
, "");
contentEle.innerHTML = template;
}
new Pagination(root, paginationConfigObj, { currentChange: renderContent });
async function ajax({ url, method = "get", data, query: { currentPage, pageSize } }) {
// TODO:根据函数参数 `query` 对象 `currentPage, pageSize` 获得当前页的数据
let result = {
data:[],
total:0
}
await axios({
methods:method,
url,
data,
query:{
currentPage, pageSize
}
}).then(res=>{
result.data=res.data.data
result.total=res.data.total
},
err=>{
console.log(err.message);
})
// console.log(result);//
return result;
}
renderPagination(indexArr) {
let template = '';
// TODO:根据 indexArr 数组生成分页组件的字符串模板 template
// console.log(indexArr);
let arr=[]
arr.push(indexArr[0])
for(let i=1;i<this.pagerCount-1;i++){
if(indexArr[i-1]!==indexArr[i]-1){
arr.push('...')
arr.push(indexArr[i])
}
else if(indexArr[this.pagerCount-1]!==indexArr[this.pagerCount-2]+1&&i===this.pagerCount-2){
arr.push(indexArr[i])
arr.push('...')
}
else arr.push(indexArr[i])
}
arr.push(indexArr[indexArr.length-1])
console.log(arr);
for(let i=0;i<arr.length;i++){
if(this.currentPage===i){
template+= `<li class="number active">${arr[i]}</li>`
}
if(arr[i]==='...'){
template+=`<li class="number more">...</li>`
}
else{
template+=`<li class="number ">${arr[i]}</li>`
}
}
this.root.innerHTML = `
<div class="pagination">
<div class="btn btn-left" id="btn-prev"><</div>
<ul class="pager">${template} </ul>
<div class="btn btn-right" id="btn-next">></div>
</div>`;
}
initEvents() {
this.root.querySelector("#btn-prev").addEventListener('click', () => {
// TODO:"<" 按钮的点击事件, 点击时 this.currentPage - 1
if(this.currentPage>1){
this.currentPage--
console.log(this.currentPage);
}
})
this.root.querySelector("#btn-next").addEventListener('click', () => {
// TODO:">" 按钮的点击事件, 点击时 this.currentPage + 1
if(this.currentPage<this.totalPages){
this.currentPage++
console.log(this.currentPage);
}
})
this.root.querySelector(".pager").addEventListener('click', (e) => {
if (e.target.nodeName.toLowerCase() === 'li') {
if (this.currentPage === e.target.innerText) return;
if (e.target.classList.contains('more')) return;
this.currentPage = Number(e.target.innerText)
}
this.initPagination();
});
}
}
const createPaginationIndexArr = (currentPage, totalPages, pagerCount) => {
let indexArr = [];
// TODO:根据传参生成分页数组 indexArr
if(totalPages<=pagerCount){
for(let i=1;i<=totalPages;i++){
indexArr.push(i)
}
}
if(totalPages>pagerCount){
indexArr.push(1)
if(currentPage<=pagerCount-2){
for(let i=2;i<pagerCount;i++){
indexArr.push(i)
}
}else if(currentPage>totalPages-pagerCount+2){
for(let i=totalPages-(pagerCount-2);i<=totalPages-1;i++){
indexArr.push(i)
}
}else{
for(let i=totalPages-(pagerCount-2);i<totalPages;i++){
indexArr.push(i)
}
}
indexArr.push(totalPages)
}
console.log(indexArr);
return indexArr;
}