angular指令彈框點擊空白處隱藏及常規方法
阿新 • • 發佈:2019-01-09
inpu click hid 效果圖 直接 fad btn ima javascrip
效果圖展示:
第一種方法: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>
深夜還在碼代碼,但是我總覺得是值得的,因為我又懂了一個知識點。
angular指令彈框點擊空白處隱藏及常規方法