如何使用以下 matchMedia 触发以下侦听器加载

问题描述 投票:0回答:1

我有以下代码。如何在屏幕默认加载或刷新时自动触发?

function screenSize(){
  const mobile = window.matchMedia('screen and (max-width: 573px)');
  const tablet = window.matchMedia('screen and (min-width: 572px) and (max-width: 990px)');
  const desktop = window.matchMedia('screen and (min-width: 990px)');

  mobile.addListener(function(evt){
    if(evt.matches) {
      alert("Mobile-view")
    }
  });

  tablet.addListener(function(evt){
    if(evt.matches) {
      alert("Tablet-view")
    }
  })

  desktop.addListener(function(evt){
    if(evt.matches) {
      alert("desktop-view")
    }
  });
}

screenSize()

仅在调整视口大小时触发。如何在视口加载或刷新时让它触发?

viewport onload matchmedia
1个回答
0
投票

根据我上面的评论,这是针对这个特定问题的解决方案。我在评论中链接的答案还有一些其他可能的解决方案。核心问题是需要在窗口或文档加载时检查查询是否有

.matches
(bool),而不仅仅是添加侦听器。

window.onload = () => {
  // set up your queries just as strings
  const mobile = 'screen and (max-width: 573px)'
  const tablet = 'screen and (min-width: 572px) and (max-width: 990px)'
  const desktop = 'screen and (min-width: 990px)'

  // loop over those as an obj so you have convenient key names
  Object.entries({ mobile, tablet, desktop })
    .forEach(([key, val]) => {
      // create a query object
      const query = window.matchMedia(val)
      // check if the query currently matches and alert if so
      if (query.matches) {
        alert(`${key}-view`)
      }

      // add the listener for resize events
      query.addListener((e) => {
        if (e.matches) {
          alert(`${key}-view`)
        }
      })
    })
}

要为每个断点使用不同的函数,你可以这样做:

window.onload = () => {
  const mobileQuery = 'screen and (max-width: 573px)'
  const tabletQuery = 'screen and (min-width: 572px) and (max-width: 990px)'
  const desktopQuery = 'screen and (min-width: 990px)'

  const mobileListener = (e) => { console.log('on mobile') }
  const tabletListener = (e) => { console.log('on tablet') }
  const desktopListener = (e) => { console.log('on desktop') }

  const breakpoints = {
    // this object has your media query strings as keys and
    // functions to run on those breakpoints as values
    [mobileQuery]: mobileListener,
    [tabletQuery]: tabletListener,
    [desktopQuery]: desktopListener
  }

  Object.entries(breakpoints)
    .forEach(([query, fn]) => {
      const q = window.matchMedia(query)
      q.addListener(fn)
      if (q.matches) fn()
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.