首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何手动触发点击事件?

如何手动触发点击事件?
EN

Stack Overflow用户
提问于 2017-08-04 02:52:58
回答 1查看 16.8K关注 0票数 7

我正在尝试以编程方式触发文档单击。

我的测试组件显示在页面中的多个位置,当单击测试组件或触发文档单击时,我希望将它们全部隐藏。

代码语言:javascript
运行
复制
@Component({
  selector: 'test-comp',
  template: `<div *ngIf="showMe">stuff</div> and more…`
})

export class TestComponent {
  showMenu: boolean;

  constructor(public elementRef: ElementRef) {
  }

  @HostListener('document:click', ['$event'])
  documentClick(event: MouseEvent) {
    //hide my component when there is a document click    
     this.toggleComponent();
  }

  toggleComponent() {
    // I am trying to programmatically fire a document click here to hide all test-comp if the test-comp   
    // component itself is clicked
    // this.elementRef.nativeElement will select all test-comp component but not sure what to do next
    this.showMe = !this.showMe;
  }

我不确定如何在我的toggleComponent方法中以编程方式触发文档单击。有办法做到这一点吗?非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-04 02:55:53

可以使用HTMLElement.click()在任何元素上触发click事件

代码语言:javascript
运行
复制
document.getElementById('myEl').click() // or the hacky id reference `myEl.click()`

您不能单击文档,因为它不是呈现的元素。但是你可以点击整个身体:

代码语言:javascript
运行
复制
document.body.click()
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45492358

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档