仅触发一次点击事件 [英] Trigger click event only once

查看:184
本文介绍了仅触发一次点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在浏览器的屏幕宽度为800px时触发click事件,但是根据以下逻辑,当我到达800并停止调整屏幕大小时,click事件会不停地来回触发.我该如何解决这个问题.

I want to trigger the click event only when the screen width of the browser is 800px, however with the logic below, the click event is triggered back and forth nonstop when i reach at the 800 and stop resizing the screen. How can i fix this issue.

html文件:

<!-- begin sidebar minify button -->
<a href="javascript:;" class="sidebar-minify-btn" data-click="sidebar-minify">
   <i class="fa fa-angle-left"></i>
</a>
<!-- end sidebar minify button -->

js文件:


window.onresize = function()
{
     const width = window.innerWidth;
     if(width === 800)
     {

        $('a[data-click="sidebar-minify"]').trigger('click');
        console.log('click event triggered');
     }
}

推荐答案

一种可能的方法是,当不再需要使用

One possible way could be to remove the resize listener when no longer needed using EventTarget.removeEventListener() like this:

function resizeListener() {
  if (window.innerWidth === 800) {
    window.removeEventListener('resize', resizeListener);
    $('a[data-click="sidebar-minify"]').trigger('click');
    console.log('click event triggered');
  }
}

window.addEventListener('resize', resizeListener);

这篇关于仅触发一次点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆