Home  >  Article  >  Web Front-end  >  JavaScript cross-browser attribute judgment method_javascript skills

JavaScript cross-browser attribute judgment method_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:55:25828browse

I discovered a very easy error while writing code today. When we declare variables, we often use the following writing method to determine which attribute is because different browsers have different API definitions, for example:

Copy code The code is as follows:
var fullscreenElement = document.mozFullScreenElement || document.webkitFullscreenElement || document.fullscreenElement;

Use || to check which attribute to use .
But be careful when judging the value of javascript as a condition.
For example:
Copy code The code is as follows:
var sLeft = window.screenLeft || window. screenX; //firefox use screenX
console.log(sLeft);

This code hopes that screenLeft will return window.screenLeft, and firefox will return window.screenX.
But if screenLeft is exactly equal to 0, it will enter the condition after ||, and then it will be gg.

Therefore, it is recommended to use hasOwnProperty or typeof to judge the value more accurately.

Copy code The code is as follows:
var sLeft = window.screenLeft;
if( !window. hasOwnProperty('screenLeft')) sLeft = window.screenX;
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn