preface

As a devout believer in JavaScript, I went back to the Bible (JavaScript Advanced Programming) in my spare time and dug out a point of knowledge — location and size of BOM window. I reviewed the development process for several years, but I didn’t use much of it. Therefore, I gradually forgot it to the corner, but I decided to write this article to deepen my impression of BOM window.

Window position

When it comes to window location, there are nasty browser compatibility issues. Here are some of the attributes that major browsers use to get window location.

  1. ScreenLeft, screenTop supports Internet Explorer, Safari, Opera, and Chrome
  2. ScreenX and screenY are supported by Firefox, Safari and Chrome. Opera also supports screenX and screenY, but does not correspond to screenLeft and screenTop

At this point I might be confident enough to give a method for getting the browser location, as follows

const leftPosition = typeOf window.screenLeft === 'number' ? window.screenLeft : window.screenX
const topPosition = typeOf window.screenTop === 'number' ? window.screenTop : window.screenY
Copy the code

but







Window size

Similarly, the browser window size also provides properties innerWidth, innerHeight, outerWidth, and outerHeigt.

  1. In IE9+ (considering IE8? OuterWidth and outerHeight return the size of the browser window. InnerWidth, innerHeight indicates the viewport size of the page (reducing the border width).
  2. In Opera, the values of the outerWidth and outerHeight properties represent the size of the page view container. InnerWidth, innerHeight indicates the viewport size of the page (reducing the border width).
  3. In Chrome, outerWidth and outerHeight return the same value as innerWidth and innerHeight, indicating the viewport size. It turns out that we can’t determine the size of the browser window itself, but we can make mistakes about the size of the page viewport. Document. documentElement contains clientWidth and clientHeight properties to describe viewport information, so you can use the following code to get the viewport size
let pageWidth = window.innerWidth,
    pageHeight = window.innerHeight
if (typeOf innerWidth ! ='number') {
    if (document.compatMode == 'CSS1Compat') {/ / strict mode pageWidth = document. DocumentElement. ClientWidth pageHeight = document. The documentElement. ClientHeight}else {
        pageWidth = document.body.clientWidth
        pageHeight = document.body.clientHeight
    }
}
Copy the code

conclusion

Generally speaking, the above is not a difficult knowledge, in the current situation of a major browser coexistence, how to compatibility is the problem. As a conscientious cutterhead, I should be grateful to the business side as long as I don’t encounter IE8 or below.