All files / dom eventOccurInside.ts

80% Statements 4/5
100% Branches 3/3
100% Functions 1/1
80% Lines 4/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                                1x   2x   2x         1x  
/**
 * 判断事件是否发生在一个 Dom 元素内。
 * - 常用于判断点击事件发生在浮层外时关闭浮层。
 * @method eventOccurInside
 * @param {Object} event 浏览器事件对象
 * @param {Object} node 用于比较事件发生区域的 Dom 对象
 * @return {Boolean} 事件是否发生在 node 内
 * @example
 * import { eventOccurInside } from '@spore-ui/tskit';
 * $('.layer').on('click', function(evt){
 *   if(eventOccurInside(evt, $(this).find('close').get(0))){
 *     $(this).hide();
 *   }
 * });
 */
 
export function eventOccurInside(event: Event, node: HTMLElement): boolean {
  if (node && event && event.target) {
    const el = event.target as HTMLElement;
    // IE9 以上即可使用 contains 方法
    return node.contains(el);
  }
  return false;
}
 
export default eventOccurInside;