1.全局添加点击事件的监听
window.addEventListener('click', this.clickOutSelectCity); // 监听是否点击除城市列表控件以外的区域
2.判断点击的dom是否在城市列表控件(class为 .BMap_CityListCtrl’)外,在外则触发控件的关闭按钮(id为 #popup_close)点击事件
clickOutSelectCity = (e) => {
const outSelectCity = !this.hasParents(e.target, '.BMap_CityListCtrl'); // 点击城市选择器以外的区域
const citylist_popup_main = document.querySelector('.citylist_popup_main');
const selectCityIsOpen = citylist_popup_main && citylist_popup_main.style.display === 'block' ? !0 : !1; // 城市选择器是否展开
if(outSelectCity && selectCityIsOpen) {
this.triggerClick();
}
}
以下为用到的方法代码(hasParents和triggerClick):
hasParents = (elClass, parentSelectorClass) => {
if (!elClass || !parentSelectorClass) {
return false;
}
let [el, parentsSelectors] = [elClass, parentSelectorClass];
if (typeof elClass === 'string') {
el = document.querySelector(elClass);
if (!el) {
return false;
}
}
if (typeof parentsSelectors === 'string') {
parentsSelectors = document.querySelectorAll(parentsSelectors);
} else {
parentsSelectors = [...parentsSelectors];
}
let hasParents = false;
for (let i = 0; i < parentsSelectors.length; i++) {
let p = el.parentNode;
while (p !== parentsSelectors[i]) {
if (!p || p === document) {
break;
}
p = p.parentNode;
}
if (p === parentsSelectors[i]) {
hasParents = true;
}
}
return hasParents;
};
triggerClick = () => { // 自动触发城市列表控件的关闭按钮
const closeBtn = document.getElementById("popup_close");
if(document.all) {
closeBtn.click();
} else {
const e = document.createEvent("MouseEvents");
e.initEvent("click", true, true);
closeBtn.dispatchEvent(e);
}
}
window.removeEventListener('click', this.clickOutSelectCity);