【问题标题】:Click event is triggered after :active selector点击事件在 :active 选择器之后触发
【发布时间】:2020-01-09 11:34:24
【问题描述】:

在我的 Angular 应用程序中,我有一个带有一点动画的按钮,当你点击它时它会下降几个像素:

&:active {
   margin: 15px 0 0 0;
}

它还有一个(click)="myFunction()" 事件监听器。

问题是,每当我点击按钮顶部时,它都不会触发该功能,因为它之前已关闭,因此点击不在按钮上。

我做了一个codeandbox来演示:https://codesandbox.io/s/angular-bx8nd?fontsize=14

有什么方法可以在点击事件后触发“活动”选择器?或者以其他方式达到同样的效果?

谢谢,

【问题讨论】:

    标签: javascript css angular button click


    【解决方案1】:

    MDN Docs:active

    :active CSS 伪类表示一个被用户激活的元素(例如按钮)。使用鼠标时,“激活”通常在用户按下鼠标主按钮时开始

    MDN Docs 获取点击事件:

    两个 mousedown 和 mouseup 事件按此顺序触发后触发。

    因此,简而言之,您的问题是因为 :active 的 css 转换在 mousedown 上触发,而 myFunction() 直到 mouseup 才会触发。

    (click)="myFunction()" 更改为(mousedown)="myFunction()",您将有一个解决方法。

    【讨论】:

      【解决方案2】:

      在 myFunction() 中添加样式,即 document.getElementById("id").style.margin="15px"。

      【讨论】:

        【解决方案3】:

        使用mouseup 事件而不是点击。

        工作小提琴 - 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>
        

        【讨论】:

          猜你喜欢
          • 2018-07-23
          • 2016-09-19
          • 2013-06-10
          • 2019-03-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-22
          相关资源
          最近更新 更多