javascript Typescript 3 Angular 7 StopPropagation 和 preventDefault 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/55551821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript 3 Angular 7 StopPropagation and PreventDefault not working
提问by user1019042
I have a text input inside a div. Clicking on the input should set it to focus and stop the bubbling of the div click event. I've tried the stopPropagationand preventDefaulton the text input event but to no avail. The console logs shows that the div click still executes regardless. How to stop the div click event from executing?
我在 div 中有一个文本输入。单击输入应将其设置为焦点并停止 div 单击事件的冒泡。我已经在文本输入事件上尝试了stopPropagation和preventDefault,但无济于事。控制台日志显示 div 单击仍然执行。如何停止执行 div 单击事件?
// html
<div (click)="divClick()" >
<mat-card mat-ripple>
<mat-card-header>
<mat-card-title>
<div style="width: 100px">
<input #inputBox matInput (mousedown)="fireEvent($event)" max-width="12" />
</div>
</mat-card-title>
</mat-card-header>
</mat-card>
</div>
// component
@ViewChild('inputBox') inputBox: ElementRef;
divClick() {
console.log('click inside div');
}
fireEvent(e) {
this.inputBox.nativeElement.focus();
e.stopPropagation();
e.preventDefault();
console.log('click inside input');
return false;
}
采纳答案by Daniel Pi?eiro
You have two different events, one is mousedownand another is click.
你有两个不同的事件,一个是mousedown,另一个是click。
The e.stopPropagation() only works if both of the events are of the same kind.
e.stopPropagation() 仅在两个事件类型相同时才有效。
You can change the input like this to work as expected:
您可以像这样更改输入以按预期工作:
<input #inputBox matInput (click)="fireEvent($event)" max-width="12" />
Live example:https://stackblitz.com/edit/angular-material-basic-stack-55598740?file=app/input-overview-example.ts
现场示例:https : //stackblitz.com/edit/angular-material-basic-stack-55598740?file=app/input-overview-example.ts
回答by Gonzalo.-
You can only stop propagation for the same event.
您只能停止同一事件的传播。
Your fireEventfunction stops propagation for your mousedownevent, but not for your clickevent.
您的fireEvent函数会停止为您的mousedown事件传播,但不会为您的click事件停止传播。
If you want to stop propagation to click, try to add another click event on the input and stop propagation from there
如果您想停止传播点击,请尝试在输入上添加另一个点击事件并从那里停止传播
For instance
例如
<input #inputBox matInput (click)="$event.stopPropagation()" max-width="12" />
Your other function only needs to know what is required, that is, set focus
你的其他功能只需要知道需要什么,即设置焦点
fireEvent(e) {
this.inputBox.nativeElement.focus();
console.log('click inside input');
}
preventDefault()prevents the default behaviour, it is not related to bubbling or not the events, so you can safely ignore it
preventDefault()防止默认行为,它与冒泡或事件无关,因此您可以放心地忽略它

