Programing

JavaScript 코드를 사용하여 브라우저 너비를 얻는 방법은 무엇입니까?

lottogame 2020. 5. 25. 08:02
반응형

JavaScript 코드를 사용하여 브라우저 너비를 얻는 방법은 무엇입니까?


현재 브라우저 너비를 얻기 위해 JavaScript 함수를 작성하려고합니다.

나는 이것을 찾았다.

javascript:alert(document.body.offsetWidth);

그러나 몸의 너비가 100 %라면 실패한다는 문제.

더 나은 기능이나 해결 방법이 있습니까?


2017 년 업데이트

원래 답변은 2009 년에 작성되었습니다. 여전히 작동하는 동안 2017 년에 업데이트하고 싶습니다. 브라우저는 여전히 다르게 동작 할 수 있습니다. jQuery 팀이 브라우저 간 일관성을 유지하는 데 큰 역할을한다고 믿습니다. 그러나 전체 라이브러리를 포함 할 필요는 없습니다. jQuery 소스에서 관련 부분은 dimension.js의 37 행에 있습니다. 여기에서 독립형으로 작동하도록 추출되고 수정됩니다.

function getWidth() {
  return Math.max(
    document.body.scrollWidth,
    document.documentElement.scrollWidth,
    document.body.offsetWidth,
    document.documentElement.offsetWidth,
    document.documentElement.clientWidth
  );
}

function getHeight() {
  return Math.max(
    document.body.scrollHeight,
    document.documentElement.scrollHeight,
    document.body.offsetHeight,
    document.documentElement.offsetHeight,
    document.documentElement.clientHeight
  );
}

console.log('Width:  ' +  getWidth() );
console.log('Height: ' + getHeight() );


원래 답변

모든 브라우저는 다르게 동작하므로 먼저 값을 테스트 한 다음 올바른 값을 사용해야합니다. 이를위한 기능은 다음과 같습니다.

function getWidth() {
  if (self.innerWidth) {
    return self.innerWidth;
  }

  if (document.documentElement && document.documentElement.clientWidth) {
    return document.documentElement.clientWidth;
  }

  if (document.body) {
    return document.body.clientWidth;
  }
}

높이와 마찬가지로 :

function getHeight() {
  if (self.innerHeight) {
    return self.innerHeight;
  }

  if (document.documentElement && document.documentElement.clientHeight) {
    return document.documentElement.clientHeight;
  }

  if (document.body) {
    return document.body.clientHeight;
  }
}

사용하여 스크립트에서이 두 가지를 전화 getWidth()또는 getHeight(). 브라우저의 기본 속성이 정의되어 있지 않으면를 반환 undefined합니다.


엉덩이아프다 . 나는 넌센스를 생략하고 사용하는 것이 좋습니다 jQuery를 그냥 수행 할 수 있습니다, $(window).width().


var w = window.innerWidth;
var h = window.innerHeight;
var ow = window.outerWidth; //including toolbars and status bar etc.
var oh = window.outerHeight;

둘 다 정수를 반환하고 jQuery가 필요하지 않습니다. 크로스 브라우저 호환

jQuery가 width () 및 height ()에 대해 잘못된 값을 반환하는 경우가 종종 있습니다.


왜 matchMedia를 언급하지 않습니까?

if (window.matchMedia("(min-width: 400px)").matches) {
  /* the viewport is at least 400 pixels wide */
} else {
  /* the viewport is less than 400 pixels wide */
}

그렇게 많이 테스트하지는 않았지만 안드로이드 기본 브라우저와 안드로이드 크롬 브라우저, 데스크탑 크롬으로 테스트했지만 지금까지는 잘 작동하는 것처럼 보입니다.

Of course it does not return number value, but returns boolean - if matches or not, so might not exactly fit the question but that's what we want anyway and probably the author of question wants.


From W3schools and its cross browser back to the dark ages of IE!

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";

alert("Browser inner window width: " + w + ", height: " + h + ".");

</script>

</body>
</html>

Here is a shorter version of the function presented above:

function getWidth() {
    if (self.innerWidth) {
       return self.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientHeight){
        return document.documentElement.clientWidth;
    }
    else if (document.body) {
        return document.body.clientWidth;
    }
    return 0;
}

참고URL : https://stackoverflow.com/questions/1038727/how-to-get-browser-width-using-javascript-code

반응형