gpt4 book ai didi

javascript - 在外部单击时,Angular 隐藏 jQuery DatePicker

转载 作者:太空宇宙 更新时间:2023-11-04 15:54:20 32 4
gpt4 key购买 nike

我在一个 Angular 项目中使用 jQuery datepicker。

<div>
<!-- Anchor that toggles date picker -->
<a class="datepicker button dropdown" ng-click="ctrl.showHideDatePicker">
<span>Choose a date</span>
</a>

<!-- Date picker -->
<div ui-date="options" ng-show="ctrl.showDatePicker"></div>
</div>

问题:日期选择器将保持打开状态,直到我选择日期或再次单击 anchor 标记。

所需结果:我希望通过单击日期选择器本身之外的任何内容来关闭日期选择器。

最佳答案

您可以向正文添加单击事件并检查目标元素是否是日期选择器。如果不是,则隐藏日期选择器。

不太理想,因为它使用了一些 jQuery,但不幸的是 jQuery UI 日期选择器没有附带 onBlur 事件。

var app = angular.module("app", ["ui.date"]);

app.controller("controller", function() {
var vm = this;

vm.showDatePicker = false;

vm.options = {
changeYear: true,
changeMonth: true,
yearRange: '1900:-0'
};

vm.hideDatePickerOnBlur = function($event) {
var $target = angular.element($event.target);

// Target is the "Choose a date" link
var isLink = $target.closest("#showDatePicker").length;
// Target is in the datepicker
var isDatePicker = $target.closest(".ui-datepicker").length;
// Target is an element in the header of the datepicker (added this because isDatePicker was false when clicking either arrow even though they are descendants of the datepicker)
var isHeader = $target.closest(".ui-datepicker-header").length;

if (!isLink && !isDatePicker && !isHeader) {
vm.showDatePicker = false;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://rawgit.com/angular-ui/ui-date/master/dist/date.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet">

<body ng-app="app" ng-controller="controller as ctrl" ng-click="ctrl.hideDatePickerOnBlur($event)">

<div>
<!-- Anchor that toggles date picker -->
<a id="showDatePicker" class="datepicker button dropdown" ng-click="ctrl.showDatePicker = true">
<span>Choose a date</span>
</a>

<!-- Date picker -->
<div ui-date="options" ng-show="ctrl.showDatePicker"></div>
</div>

</body>

关于javascript - 在外部单击时,Angular 隐藏 jQuery DatePicker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42845632/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com