【问题标题】:Determine what is the screen width of the browser确定浏览器的屏幕宽度是多少
【发布时间】:2020-10-22 15:29:02
【问题描述】:

我在 Google 上搜索过这个问题,但仍然没有找到解决方案。所以基本上我想删除特定屏幕宽度上的类名。我有一个运行良好的代码,但它存在问题,我将举例说明问题所在。在我设置的代码中,当页面达到 850px 时,它将删除类名并且它工作正常但是当我刷新页面时,例如在 500px 上它不会删除类名,当我开始调整页面大小时它会删除类名。所以我想要的是当我在 500px 上刷新页面时,它会删除类名

有什么办法可以解决这个问题吗?

代码如下:

window.addEventListener('resize', function(event){
        if(window.matchMedia("(max-width: 850px)").matches){
            var poster = document.getElementById('poster');
            poster.classList.remove('fade')

            var bgtariler = document.getElementById('bg-trailer');
            bgtariler.classList.remove('fade')

            var mutebt = document.getElementById('muted-button');
            mutebt.classList.remove('fade') 
        }
        else if(video.ended){
            document.getElementById('bg-trailer').addEventListener('ended', function(){
                var poster = document.getElementById('poster');
                poster.classList.remove('fade')

                var bgtariler = document.getElementById('bg-trailer');
                bgtariler.classList.remove('fade')

                var mutebt = document.getElementById('muted-button');
                mutebt.classList.remove('fade')
            },false);
        }
        else{
            var poster = document.getElementById('poster');
            poster.classList.add('fade')

            var bgtariler = document.getElementById('bg-trailer');
            bgtariler.classList.add('fade')

            var mutebt = document.getElementById('muted-button');
            mutebt.classList.add('fade') 
        }
    })

【问题讨论】:

  • 添加像onended这样的事件监听器应该只做一次,而不是每个onresize事件,如果你想要在刷新页面时调整大小的相同行为,你可以分配事件onresizeonload 的监听器函数

标签: javascript width screen


【解决方案1】:

尝试在load 事件中重用相同的函数,它会是这样的

function handleFadeClass() {
  /* Your function */
}

window.addEventListener('load', handleFadeClass);
window.addEventListener('resize', handleFadeClass);

【讨论】:

    猜你喜欢
    • 2012-10-25
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多