只触发一次点击事件

我只想在浏览器的屏幕宽度为 800 像素时触发点击事件,但是按照下面的逻辑,当我到达 800 并停止调整屏幕大小时,点击事件会不停地来回触发。我该如何解决这个问题。


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');

     }

}


开心每一天1111
浏览 263回答 3
3回答

慕哥9229398

一种可能的方法是resize在不再需要时使用EventTarget.removeEventListener()删除侦听器,如下所示:function resizeListener() {&nbsp; if (window.innerWidth === 800) {&nbsp; &nbsp; window.removeEventListener('resize', resizeListener);&nbsp; &nbsp; $('a[data-click="sidebar-minify"]').trigger('click');&nbsp; &nbsp; console.log('click event triggered');&nbsp; }}window.addEventListener('resize', resizeListener);

函数式编程

就像@Pete 在评论中所说的那样,您有不同的选择。您可以使用布尔值来跟踪事件是否已被触发:var isResized = false;window.onresize = function(){&nbsp; &nbsp; &nbsp;const width = window.innerWidth;&nbsp; &nbsp; &nbsp;if(width === 800 && !isResized)&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; isResized = true;&nbsp; &nbsp; &nbsp; &nbsp; alert("test");&nbsp; &nbsp; &nbsp;}}您还可以使用one单击的功能,a tag在第一次使用后解除单击的绑定:window.onresize = function(){&nbsp; &nbsp; &nbsp;const width = window.innerWidth;&nbsp; &nbsp; &nbsp;if(width === 800)&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; $('a[data-click="sidebar-minify"]').trigger('click');&nbsp; &nbsp; &nbsp; &nbsp; console.log('click event triggered');&nbsp; &nbsp; &nbsp;}}$('a[data-click="sidebar-minify"]').one("click", function(){&nbsp; &nbsp; alert("test");});

呼唤远方

window.onresize = function(){&nbsp;const width = window.innerWidth;&nbsp;if(width === 800)&nbsp;{&nbsp; &nbsp;// give anker link class then remove that after condition true&nbsp; &nbsp; $('.anker').trigger('click');&nbsp; &nbsp; console.log('click event triggered');&nbsp; &nbsp;$('a[data-click="sidebar-minify"]').removeClass("anker");&nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript