简体   繁体   中英

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. 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. Means: The parallax scrolling is also enabled for screen smaller than 800px.

Any help is appreciated!

What you're looking for is 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 .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM