Chinaunix首页 | 论坛 | 博客
  • 博客访问: 458360
  • 博文数量: 226
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2111
  • 用 户 组: 普通用户
  • 注册时间: 2014-06-20 09:02
个人简介

web web web

文章分类

全部博文(226)

文章存档

2020年(2)

2019年(1)

2018年(3)

2017年(26)

2016年(57)

2015年(60)

2014年(77)

我的朋友

分类: Web开发

2017-05-10 09:57:41

setBgColor.js

  1. //分号开头,用于防止代码压缩合并时与其它代码混在一起造成语法错误
  2. //而事实证明,uglify压缩工具会将无意义的前置分号去掉,我只是习惯了这么写
  3. //(function(){})();立即执行函数,闭包,避免污染全局变量
  4. //开启严格模式,规范代码,提高浏览器运行效率
  5. //定义一个类,通常首字母大写
  6. //覆写原型链,给继承者提供方法
  7. //兼容CommonJs规范
  8. //兼容AMD/CMD规范
  9. //注册全局变量,兼容直接使用script标签引入该插件
  10. ;
  11. (function(){
  12.     "use strict";
  13.     var MyPlugin = function(options) {
  14.         this.options = typeof options === "string" ? document.querySelector(options) : options;
  15.     };

  16.     MyPlugin.prototype = {
  17.         setBg: function(bg) {
  18.             this.options.style.background = bg;
  19.         }
  20.     };

  21.     if (typeof module !== 'undefined' && module.exports){
  22.         module.exports = MyPlugin;    
  23.     }else if (typeof define !== 'undefined' && define.amd){
  24.         define("MyPlugin",[],function() {
  25.             return MyPlugin;
  26.         });
  27.     }else{
  28.         window.ModifyDivBg = MyPlugin;
  29.     }

  30. })(this);
index.html

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">

  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>怎样写一个js插件</title>
  6.     <script src="./setBgColor.js"></script>
  7. </head>
  8. <body>
  9.     <div id="div">怎样写一个js插件</div>
  10.     <script>
  11.     var mObj = new ModifyDivBg("#div");
  12.     mObj.setBg("green");
  13.     </script>
  14. </body>
  15. </html>

阅读(552) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~