简体   繁体   English

仅当最小宽度为800px时才执行Javascript

[英]Executing Javascript only if min-width is 800px

For my project I want a parallax scrolling effect only if the screen size is equal or wider than 800px. 对于我的项目,仅当屏幕尺寸等于或大于800px时,我才需要视差滚动效果。 To do this I wrote following code: 为此,我编写了以下代码:

<script>
    if (window.screen.width >= 800) {
        function parallax() {
            var parallax = document.getElementById("box01");
            parallax.style.top = -(window.pageYOffset / 4) + "px";

        }
    }

    window.addEventListener("scroll", parallax, false);

</script>

The parallax scrolling works fine but the "window.screen.width" command is ignored by the browser. 视差滚动工作正常,但浏览器将忽略“ window.screen.width”命令。 Means: The parallax scrolling is also enabled for screen smaller than 800px. 意思是:小于800像素的屏幕也启用了视差滚动。

Any help is appreciated! 任何帮助表示赞赏!

What you're looking for is window.matchMedia . 您正在寻找的是window.matchMedia

function executeIfMinWidth800 (e) {
  if (window.matchMedia('(min-width: 800px)').matches) {
    // do stuff
  }
}

// call initially
executeIfMinWidth800();

// add handler for resize
window.addEventListener('resize', executeIfMinWidth800);

window.screen gets you the size of the monitor . window.screen让您获得显示器的大小。

What you want is the size of the viewport , accessible via: 您想要的是视口的大小,可通过以下方式访问:

// width
window.innerWidth
// height
window.innerHeight

You should try this 你应该试试这个

if (window.matchMedia('(min-width: 800px)').matches) {
  function parallax() {
        var parallax = document.getElementById("box01");
        parallax.style.top = -(window.pageYOffset / 4) + "px";

    }
} else {};
window.addEventListener("scroll", parallax, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript-如果窗口宽度&lt;= 800px,则将活动链接移至导航顶部 - Javascript - Move active link to top of navigation if window-width <= 800px 如何使此JavaScript仅适用于最小宽度为1036px的浏览器上的用户? - How do I make this JavaScript only work for users on browsers with a min-width of 1036px? 仅为最小宽度加载 javascript - Load javascript only for min-width 如果窗口宽度在800px至799px之间,则执行JS函数 - Do JS function if window width between 800px and 799px JS-窗口的宽度从高于800px的像素数量减少到800px以下导致触发动作 - JS - Window's width being decreased below 800px from an amount of pixels that are higher than 800px causes an action to trigger 如何删除javascript src,如果@media(min-width:xxx px){ - How to remove javascript src's if @media (min-width:xxx px) { jQuery min-width vs width:如何删除px? - jQuery min-width vs width: How to remove px? 使用Javascript代码的媒体查询最小宽度 - Media query min-width with Javascript code 当我的窗口宽度小于800px时,如何将js滑块效果更改为淡入淡出? - how do i change the js slider effect to fade when my window width is less than 800px? 如果窗口宽度大于800px时刷新站点,则jQuery click事件不起作用 - jQuery click event doesn't work if I refresh site when window width is bigger than 800px
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM