:active 选择器后触发点击事件
Click event is triggered after :active selector
在我的 Angular 应用程序中,我有一个带有小动画的按钮,单击它时它会下降几个像素:
&:active {
margin: 15px 0 0 0;
}
它还有一个 (click)="myFunction()"
事件侦听器。
问题是每当我点击按钮的顶部时,它都不会触发该功能,因为它之前会下降,因此点击不在按钮上。
我做了一个codesandbox来演示:https://codesandbox.io/s/angular-bx8nd?fontsize=14
有什么方法可以让 'active' 选择器在点击事件后触发吗?或者以其他方式达到同样的效果?
谢谢,
来自 MDN Docs for :active
:
The :active CSS pseudo-class represents an element (such as a button) that is being activated by the user. When using a mouse, "activation" typically starts when the user presses down the primary mouse button.
并且来自 MDN Docs 的点击事件:
click fires after both the mousedown and mouseup events have fired, in that order.
所以,简而言之,您的问题是因为 :active
的 css 转换在 mousedown
上触发,而 myFunction()
直到 mouseup
.
将 (click)="myFunction()"
更改为 (mousedown)="myFunction()"
,您将有一个解决方法。
添加样式,即 document.getElementById("id").style.margin="15px" inside the myFunction().
使用 mouseup
事件而不是点击。
工作 Fiddle - https://codesandbox.io/s/angular-2z45i?fontsize=14
test() {
const btn = document.querySelector("button");
btn.style.margin = "15px 0 0 0";
this.clicked++;
setTimeout(() => {
btn.style.margin = "";
}, 100);
}
--HTML--
<button class="btn" (mouseup)="test()">Test</button>
在我的 Angular 应用程序中,我有一个带有小动画的按钮,单击它时它会下降几个像素:
&:active {
margin: 15px 0 0 0;
}
它还有一个 (click)="myFunction()"
事件侦听器。
问题是每当我点击按钮的顶部时,它都不会触发该功能,因为它之前会下降,因此点击不在按钮上。
我做了一个codesandbox来演示:https://codesandbox.io/s/angular-bx8nd?fontsize=14
有什么方法可以让 'active' 选择器在点击事件后触发吗?或者以其他方式达到同样的效果?
谢谢,
来自 MDN Docs for :active
:
The :active CSS pseudo-class represents an element (such as a button) that is being activated by the user. When using a mouse, "activation" typically starts when the user presses down the primary mouse button.
并且来自 MDN Docs 的点击事件:
click fires after both the mousedown and mouseup events have fired, in that order.
所以,简而言之,您的问题是因为 :active
的 css 转换在 mousedown
上触发,而 myFunction()
直到 mouseup
.
将 (click)="myFunction()"
更改为 (mousedown)="myFunction()"
,您将有一个解决方法。
添加样式,即 document.getElementById("id").style.margin="15px" inside the myFunction().
使用 mouseup
事件而不是点击。
工作 Fiddle - https://codesandbox.io/s/angular-2z45i?fontsize=14
test() {
const btn = document.querySelector("button");
btn.style.margin = "15px 0 0 0";
this.clicked++;
setTimeout(() => {
btn.style.margin = "";
}, 100);
}
--HTML--
<button class="btn" (mouseup)="test()">Test</button>