最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to unbind a scroll event added to the window only using Javascript? - Stack Overflow

programmeradmin2浏览0评论

I have added a scroll event to the window using the below code.

window.onscroll=function () {

How to unbind this scroll event added to the window only by using Javascript?

I have added a scroll event to the window using the below code.

window.onscroll=function () {

How to unbind this scroll event added to the window only by using Javascript?

Share Improve this question edited Jan 26, 2021 at 17:45 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Sep 8, 2015 at 19:36 SareeshSareesh 851 silver badge9 bronze badges 2
  • With window.onscroll = function(){}? – Kyll Commented Sep 8, 2015 at 19:38
  • @Sareesh you should accept the answer of AdamJB – Jannie Theunissen Commented Oct 9, 2018 at 6:20
Add a ment  | 

2 Answers 2

Reset to default 5

The answer from VRFP is slightly incorrect. The event listeners should be added and removed with 'scroll' as the event as follows:

window.addEventListener('scroll', myFunction, false);

window.removeEventListener('scroll', myFunction, false);

also, the function can be either an expression or declaration, it doesn't matter. Just be aware of function hoisting.

Function expression:

var myFunction = function() {
   /* do something here */
};

Function declaration:

function myFunction() {
   /* do something here */
};

Use

var myFunction = function (event) {
   /* do something here */
};

window.addEventListener('onscroll', myFunction, false )

window.removeEventListener('onscroll', myFunction, false)

https://developer.mozilla/en-US/docs/Web/API/EventTarget/removeEventListener

发布评论

评论列表(0)

  1. 暂无评论