简体   繁体   中英

How to constantly return screen width/height in JavaScript?

I am trying to make a website responsive according to the screen width but using only javascript... So for that, I need a fucntion which constantly returns the screen width without stopping. Any solutions??

I did not write this hook, but it is a very useful react hook for doing just what you are asking.

import { useEffect, useState } from 'react'

export function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined
  })

  useEffect(() => {
    function handleResize() {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight
      })
    }

    window.addEventListener('resize', handleResize)
    handleResize()

    return () => window.removeEventListener('resize', handleResize)
  }, [])

  return windowSize
}

and you would call it in your react component like so:

const windowSize = useWindowSize()


here is a similar concept via vanilla JS

function handleResize() {
  let newHeight = window.innerHeight;
  let newWidth = window.innerWidth;
  document.getElementById(
    "app"
  ).innerHTML = `width: ${newWidth}, height: ${newHeight}`;
}

window.addEventListener("resize", handleResize);
// calling the function for the first time
handleResize();

you can also view a code sandbox of how the vanilla js example works: https://codesandbox.io/s/wild-cookies-n0ih6g?file=/src/index.js:0-308

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