[英]How to close div when div loses focus?
我在這里做了一個簡單的plunkr http://plnkr.co/edit/zNb65ErYH5HXgAQPOSM0?p=preview
我創建了一個小日期選擇器,如果我對輸入進行模糊處理,我希望它在關閉時自動關閉(日期選擇器的聚焦),但是我無法使用日期選擇器,如果我將焦點輸出事件放在日期選擇器上,它將無法正常工作
我也嘗試過:
angular.element(theCalendar).bind('blur', function () {
$scope.hideCalendar();
});
但這不起作用。
有什么線索嗎?
這是因為您在有機會做任何事情之前就刪除了該項目,這是一個有效的示例:
http://plnkr.co/edit/mDfV9NLAQCP4l7wHdlfi?p=preview
只需添加一個超時:
thisInput.bind('blur', function () {
$timeout(function(){
$scope.hideCalendar();
}, 200);
});
您是否考慮過使用現有的日期選擇器? 像angularUI或angular-strap: http ://mgcrea.github.io/angular-strap/##datepickers
更新:
不是一個完整的解決方案,但應該可以使您更加接近:
angular.element($document[0].body).bind('click', function(e){
console.log(angular.element(e.target), e.target.nodeName)
var classNamed = angular.element(e.target).attr('class');
var inThing = (classNamed.indexOf('datepicker-calendar') > -1);
if (inThing || e.target.nodeName === "INPUT") {
console.log('in');
} else {
console.log('out');
$timeout(function(){
$scope.hideCalendar();
}, 200);
}
});
http://plnkr.co/edit/EbQl5xsCnG837rAEhBZh?p=preview
然后,您要做的就是監聽頁面上的單擊,如果單擊不在日歷中,則將其關閉,否則不執行任何操作。 上面僅考慮到您單擊的類名稱包括datepicker-calendar的東西,您需要對其進行調整,以便在日歷中單擊也不會將其關閉。
鼠標關閉時如何關閉?
但是,如果您移至日歷中的另一個div,則需要取消關閉:
//get the calendar as element
theCalendar = element[0].children[1];
// hide the calendar on mouseout
var closeCalendarTimeout = null;
angular.element(theCalendar).bind('mouseout', function () {
if ( closeCalendarTimeout !== null )
$timeout.cancel(closeCalendarTimeout);
closeCalendarTimeout = $timeout(function () {
$scope.hideCalendar();
},250)
});
angular.element(theCalendar).bind('mouseover', function () {
if ( closeCalendarTimeout === null ) return
$timeout.cancel(closeCalendarTimeout);
closeCalendarTimeout = null;
});
編輯
向div添加tabindex屬性會導致其觸發焦點並模糊事件。
, htmlTemplate = '<div class="datepicker-calendar" tabindex="0">' +
angular.element(theCalendar).bind('blur', function () {
$scope.hideCalendar();
});
因此,我知道這可能不是最佳實踐或最佳方法,但最后我固定並獲得了使用此方法所需的功能:
thisInput.bind('focus click', function bindingFunction() {
isMouseOnInput = true;
$scope.showCalendar();
angular.element(theCalendar).triggerHandler('focus');
});
thisInput.bind('blur focusout', function bindingFunction() {
isMouseOnInput = false;
});
angular.element(theCalendar).bind('mouseenter', function () {
isMouseOn = true;
});
angular.element(theCalendar).bind('mouseleave', function () {
isMouseOn = false;
});
angular.element($window).bind('click', function () {
if (!isMouseOn && !isMouseOnInput) {
$scope.hideCalendar();
}
});
我設置了一些布爾變量,以檢查單擊頁面時鼠標的位置,如果您有更好的解決方案可以工作,它就像一個超級按鈕,請讓我知道,但這實際上已解決了所有問題。
我接受這個作為答案,但是我感謝本頁上的所有人!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.