效果图展示:
第一种方法:angularjs自定义指令:
指令:
app.directive('onBlankHide', function () {
return {
restrict: 'A',
scope: {
pop: '='
},
link: function (scope, element, attr) {
element.on('click', function (e) {
$('#' + scope.pop).fadeIn();
$(document).click(function () {
$('#' + scope.pop).hide();
});
//阻止底层冒泡
e.stopPropagation();
});
$('#' + scope.pop).click(function (e) {
//阻止底层冒泡
e.stopPropagation();
})
}
}
});
调用方法:
<input id="btn" type="button" value="显示DIV" on-blank-hide pop="'myDiv'" /> <div id="myDiv"> This is a div; </div>
说明:pop是向指令传递的值,表示关联弹框的id名,不要忘‘’
完整栗子(代码可直接copy):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script> <title>Document</title> <style type="text/css"> body { background-color: #999999; } #myDiv { background-color: #FFFFFF; width: 250px; height: 250px; display: none; } </style> </head> <body ng-app="myApp"> <input id="btn" type="button" value="显示DIV" on-blank-hide pop="'myDiv'" /> <div id="myDiv"> This is a div; </div> </body> <script type="text/javascript"> var app = angular.module("myApp", []); app.directive('onBlankHide', function () { return { restrict: 'A', scope: { pop: '=' }, link: function (scope, element, attr) { element.on('click', function (e) { $('#' + scope.pop).fadeIn(); $(document).click(function () { $('#' + scope.pop).hide(); }); //阻止底层冒泡 e.stopPropagation(); }); $('#' + scope.pop).click(function (e) { //阻止底层冒泡 e.stopPropagation(); }) } } }); </script> </html>
常规方法(代码可直接copy):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <title>Document</title> <style type="text/css"> body { background-color: #999999; } #myDiv { background-color: #FFFFFF; width: 250px; height: 250px; display: none; } </style> </head> <body> <input id="btn" type="button" value="显示DIV" /> <div id="myDiv"> This is a div; </div> </body> <script type="text/javascript"> $(function () { $("#btn").click(function (event) { $('#myDiv').fadeIn(); $(document).one("click", function () { //对document绑定一个影藏Div方法 $('#myDiv').hide(); }); event.stopPropagation(); //阻止事件向上冒泡 }); $('#myDiv').click(function (event) { event.stopPropagation(); //阻止事件向上冒泡 }); }); </script> </html>
深夜还在码代码,但是我总觉得是值得的,因为我又懂了一个知识点。