gpt4 book ai didi

javascript - 使用 Angular 检测对 iframe 的点击

转载 作者:行者123 更新时间:2023-12-01 00:46:25 27 4
gpt4 key购买 nike

当用户单击弹出窗口外部时,我想关闭多选下拉弹出窗口。当用户单击 IFrame 外部时,它工作正常。但是当用户点击 iframe 弹出窗口时并没有关闭。我正在尝试添加一些补丁代码,但为此我需要检测 Iframe 上的点击事件。我看到了太多的例子,但没有得到很好的解决方案。

 @HostListener('click', ['$event.target'])
onClick() {
console.log('iframe clicked');
}

我已经尝试过上面的代码,但 onClick 方法没有在 iframe 点击时调用。

注意:我需要检测每个点击事件,而不仅仅是第一次点击。

最佳答案

你可以尝试这个 Angular 指令:

import {
Directive,
ElementRef,
OnInit,
Renderer2,
Input,
Output,
EventEmitter,
HostListener
} from '@angular/core';

@Directive({
selector: '[appIframeTracker]'
})
export class IframeTrackerDirective implements OnInit {
private iframeMouseOver: boolean;

@Input() debug: boolean;

@Output() iframeClick = new EventEmitter<ElementRef>();

constructor(private el: ElementRef, private renderer: Renderer2) {}

ngOnInit(): void {
this.renderer.listen(window, 'blur', () => this.onWindowBlur());
}

@HostListener('mouseover')
private onIframeMouseOver() {
this.log('Iframe mouse over');
this.iframeMouseOver = true;
this.resetFocusOnWindow();
}

@HostListener('mouseout')
private onIframeMouseOut() {
this.log('Iframe mouse out');
this.iframeMouseOver = false;
this.resetFocusOnWindow();
}

private onWindowBlur() {
if (this.iframeMouseOver) {
this.log('WOW! Iframe click!!!');
this.resetFocusOnWindow();
this.iframeClick.emit(this.el);
}
}

private resetFocusOnWindow() {
setTimeout(() => {
this.log('reset focus to window');
window.focus();
}, 100);
}

private log(message: string) {
if (this.debug) {
console.log(message);
}
}
}

当我们点击 IFrame 时,它​​会发出一个输出事件。

来源:https://gist.github.com/micdenny/db03a814eaf4cd8abf95f77885d9316f

希望对您有所帮助。

关于javascript - 使用 Angular 检测对 iframe 的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57309735/

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