快速封装js插件教程
以封装一个轮播图插件为例,教你快速封装一个自己的原生js插件
- 创建三个文件,名字分别为 swiper.js,swiper.css,index.html,其中 swiper.js,swiper.css分别为插件swiper的js和css文件,index.html为使用示例
- 在swiper.js文件中先粘贴以下封装模板
!function (t,e){
"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("swiper",[],e):t.swiper=e()
}(this,function(){
//工具类函数
'use strict' //严格模式 ES5提出
//模块代码的公用工具类
function isObj(obj){
return typeof obj==='object' && obj!==null
}
function isArray(arr){
return arr.constructor===Array;
}
return function(){
if(!isObj(obj)|| isArray(obj)){
//console.log('数据类型错误')
throw new Error('数据类型错误')
}
}
})
当创建自己的插件时,记住把第二行的两处swiper换成自己的插件名称即可
- 在html中粘贴以下使用插件的模板
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>swiper插件</title>
<script src="swiper.js"></script>
<link href="swiper.css" rel="stylesheet" />
</head>
<body>
<div id="#box"></div>
</body>
<script>
var data={},
new swiper({
el:'#box',//包裹轮播图的最外层div
data:data,//轮播图中要展示的数据
})
</script>
</html>
- 在return function 函数中