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

javascript - matchMedia removeListener doesn't work? - Stack Overflow

programmeradmin2浏览0评论

I am trying to use the matchMedia / mediaQuery Web Api - I can successfully add a listener, but I am unable to remove the listener.

What am I missing?

This code demonstrates the problem - try printing the page - note you get TEST logged in the console even though you shouldn't...

var test=function(){
    console.log("TEST")
}

window.matchMedia('print').addListener(test);
window.matchMedia('print').removeListener(test);

I've tested and this occurs on both Chrome and Safari

I am trying to use the matchMedia / mediaQuery Web Api - I can successfully add a listener, but I am unable to remove the listener.

What am I missing?

This code demonstrates the problem - try printing the page - note you get TEST logged in the console even though you shouldn't...

var test=function(){
    console.log("TEST")
}

window.matchMedia('print').addListener(test);
window.matchMedia('print').removeListener(test);

I've tested and this occurs on both Chrome and Safari

Share Improve this question asked Sep 9, 2014 at 3:10 xlfexlfe 1482 silver badges7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

You’re creating a new media query list each time, so you’re not able to remove the listener from the first query.

var m = window.matchMedia('print');
m.addListener(test);
m.removeListener(test);
发布评论

评论列表(0)

  1. 暂无评论