1 如何使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<link href="bootstrap.css" rel="stylesheet">
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
</head>
<body>
<div class="container">
<div class="alert alert-success " role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Warning!</strong> Better check yourself, you're not looking too good.
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="bootstrap.js"></script>
<script>
</script>
</body>
</html>
2 整体结构
(function ($) {
//构造函数
var Alert = function (el) {};
//静态变量
Alert.VERSION = '3.3.7';
//原型方法
Alert.prototype.close=function () {};
//插件入口
function Plugin(option) {}
var old = $.fn.alert;
$.fn.alert = Plugin;//暴露插件
$.fn.alert.Constructor = Alert;//指向构造函数
//防冲突处理
$.fn.alert.noConflict = function () {};
//data-api实现
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
})(jQuery);
3 插件入口
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert');
//实例化构造函数,保存到自定义数据中
if (!data) $this.data('bs.alert', (data = new Alert(this)));
//如果参数是字符串,就执行原型方法
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert;
$.fn.alert = Plugin;
$.fn.alert.Constructor = Alert;
$.fn.alert.noConflict = function () {
$.fn.alert = old;
return this
};
4 data-api实现
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
5 构造函数+静态变量
//关闭按钮选择器
var dismiss = '[data-dismiss="alert"]';
//提醒框构造函数
var Alert = function (el) {
//绑定原型上的关闭事件
$(el).on('click', dismiss, this.close)
};
Alert.VERSION = '3.3.7';//插件版本
Alert.TRANSITION_DURATION = 150;//动画时间
6 原型方法
Alert.prototype.close = function (e) {
var $this = $(this);//关闭按钮
var selector = $this.attr('data-target');//获取data-target
if (!selector) {
selector = $this.attr('href');//没有就是href
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '');
}
var $parent = $(selector === '#' ? [] : selector);
if (e) e.preventDefault();//取消链接的跳转
if (!$parent.length) {
//没有$parent,就是最近的.alert
$parent = $this.closest('.alert')
}
//触发自定义关闭事件
$parent.trigger(e = $.Event('close.bs.alert'));
if (e.isDefaultPrevented()) return;
$parent.removeClass('in');
function removeElement() {
//移除对话框并触发关闭事件
// detach()删除元素,jq还有、remove()删除所有
$parent.detach().trigger('closed.bs.alert').remove()
}
//支持动画
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
};
网友评论