A brief discussion on browser compatibility issues in JavaScript

A brief discussion on browser compatibility issues in JavaScript

Browser compatibility is the most important part that is easily overlooked in actual development. Before we talk about the compatibility issues of older versions of browsers, we must first understand what capability detection is. It is used to detect whether the browser has this capability, that is, to determine whether the current browser supports the properties or methods to be called. Some brief introductions are given below.

1. innerText and innerContent
1) innerText and innerContent have the same function
2) innerText is supported by browsers before IE8
3) innerContent Old version of Firefox supports
4) New versions of browsers support both methods

JavaScript CodeCopy content to clipboard
  1. // Old version browsers are compatible with innerText and innerContent   
  2.    if (element.textContent) {
  3.          return element.textContent;
  4. } else {
  5.         return element.innerText;
  6. }

2. Compatibility issues in obtaining sibling nodes/elements

1) Brother nodes, supported by all browsers

①nextSibling The next sibling node, which may be a non-element node; the text node will be obtained

②previousSibling The previous sibling node, which may be a non-element node; the text node will be obtained

2) Brother elements, not supported before IE8

①previousElementSibling gets the previous adjacent sibling element, ignoring blank spaces

②nextElementSibling gets the next adjacent sibling element, ignoring blanks

JavaScript CodeCopy content to clipboard
  1. //Compatible browsers   
  2. // Get the next adjacent sibling element   
  3. function getNextElement(element) {
  4.     // Capability test   
  5.    if (element.nextElementSibling) {
  6.        return element.nextElementSibling;
  7. } else {
  8.           var node = element.nextSibling;
  9.           while (node ​​&& node.nodeType !== 1) {
  10. node = node.nextibling;
  11. }
  12.           return node;
  13. }
  14. }

JavaScript CodeCopy content to clipboard
  1. /**
  2. * Returns the previous element
  3. * @param element
  4. * @returns {*}
  5. */   
  6. function getPreviousElement(element) {
  7.      if (element.previousElementSibling) {
  8.          return element.previousElementSibling;
  9. } else {
  10.          var el = element.previousSibling;
  11.          while (el && el.nodeType !== 1) {
  12. el = el.previousSibling;
  13. }
  14.          return el;
  15. }
  16. }
JavaScript CodeCopy content to clipboard
  1. /**
  2. * Returns the browser compatibility of the first element firstElementChild
  3. * @param parent
  4. * @returns {*}
  5. */   
  6. function getFirstElement(parent) {
  7.      if (parent.firstElementChild) {
  8.          return parent.firstElementChild;
  9. } else {
  10.          var el = parent.firstChild;
  11.          while (el && el.nodeType !== 1) {
  12. el = el.nextSibling;
  13. }
  14.          return el;
  15. }
  16. }
JavaScript CodeCopy content to clipboard
  1. /**
  2. * Return the last element
  3. * @param parent
  4. * @returns {*}
  5. */   
  6. function getLastElement(parent) {
  7.      if (parent.lastElementChild) {
  8.          return parent.lastElementChild;
  9. } else {
  10.          var el = parent.lastChild;
  11.          while (el && el.nodeType !== 1) {
  12. el = el.previousSibling;
  13. }
  14.          return el;
  15. }
  16. }
JavaScript CodeCopy content to clipboard
  1. /**
  2. * Get all sibling elements of the current element
  3. * @param element
  4. * @returns {Array}
  5. */   
  6. function sibling(element) {
  7.      if (!element) return ;
  8.        
  9.      var elements = [ ];
  10.      var el = element.previousSibling;
  11.      while (el) {
  12.          if (el.nodeType === 1) {
  13. elements.push(el);
  14. }
  15. el = el.previousSibling;
  16. }
  17. el = element.previousSibling;
  18.       while (el ) {
  19.          if (el.nodeType === 1) {
  20. elements.push(el);
  21. }
  22. el = el.nextSibling;
  23. }
  24.          return elements;
  25. }

3. array.filter();

// Test all elements using the specified function and create a new array containing all elements that pass the test

JavaScript CodeCopy content to clipboard
  1. // Compatible with old environment   
  2. if (!Array.prototype.filter)
  3. {
  4. Array.prototype.filter = function (fun /*, thisArg */ )
  5. {
  6.      "use strict" ;
  7.      if ( this === void 0 || this === null )
  8.        throw   new TypeError();
  9.      var t = Object( this );
  10.      var len = t.length >>> 0;
  11.      if ( typeof fun !== "function" )
  12.        throw   new TypeError();
  13.      var res = [];
  14.      var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  15.      for ( var i = 0; i < len; i++)
  16. {
  17.        if (i in t)
  18. {
  19.          var val = t[i];
  20.          // NOTE: Technically this should Object.defineProperty at   
  21.          // the next index, as push can be affected by   
  22.          // properties on Object.prototype and Array.prototype.   
  23.          // But that method's new, and collisions should be   
  24.          // rare, so use the more-compatible alternative.   
  25.          if (fun.call(thisArg, val, i, t))
  26. res.push(val);
  27. }
  28. }
  29.      return res;
  30. };
  31. }

4. array.forEach();
// Traverse the array
JavaScript CodeCopy content to clipboard
  1. //Compatible with old environment   
  2. // Production steps of ECMA-262, Edition 5, 15.4.4.18   
  3. // Reference: http://es5.github.io/#x15.4.4.18   
  4. if (!Array.prototype.forEach) {
  5. Array.prototype.forEach = function (callback, thisArg) {
  6.      var T, k;
  7.      if ( this == null ) {
  8.        throw   new TypeError( ' this is null or not defined' );
  9. }
  10.      // 1. Let O be the result of calling toObject() passing the   
  11.      // |this| value as the argument.   
  12.      var O = Object( this );
  13.      // 2. Let lenValue be the result of calling the Get() internal   
  14.      // method of O with the argument "length".   
  15.      // 3. Let len ​​be toUint32(lenValue).   
  16.      var len = O.length >>> 0;
  17.      // 4. If isCallable(callback) is false, throw a TypeError   
  18. exception. // See: http://es5.github.com/#x9.11   
  19.      if ( typeof callback !== "function" ) {
  20.        throw   new TypeError(callback + ' is not a function' );
  21. }
  22.      // 5. If thisArg was supplied, let T be thisArg; else let   
  23.      // T is undefined.   
  24.      if (arguments.length > 1) {
  25. T = thisArg;
  26. }
  27.      // 6. Let k be 0   
  28. k = 0;
  29.      // 7. Repeat, while k < len   
  30.      while (k < len) {
  31.        var kValue;
  32.        // a. Let Pk be ToString(k).   
  33.        // This is implicit for LHS operands of the in operator   
  34.        // b. Let kPresent be the result of calling the HasProperty   
  35.        // internal method of O with argument Pk.   
  36.        // This step can be combined with c   
  37.        // c. If kPresent is true, then   
  38.        if (k in O) {
  39.          // i. Let kValue be the result of calling the Get internal   
  40.          // method of O with argument Pk.   
  41. kValue = O[k];
  42.          // ii. Call the Call internal method of callback with T as   
  43.          // the this value and argument list containing kValue, k, and O.   
  44. callback.call(T, kValue, k, O);
  45. }
  46.        // d. Increase k by 1.   
  47. k++;
  48. }
  49.      // 8. return undefined   
  50. };
  51. }

5. Registration Events
JavaScript CodeCopy content to clipboard
  1. .addEventListener = function (type,listener,useCapture ) { };
  2. //The first parameter event name   
  3. //The second parameter event processing function (listener)   
  4. //The third parameter true capture false bubble   
  5. //Supported only after IE9
  6. // Compatible with old environment   
JavaScript CodeCopy content to clipboard
  1. var EventTools = {
  2. addEventListener: function (element, eventName, listener) {
  3.              //Capability test   
  4.              if (element.addEventListener) {
  5. element.addEventListener(eventName, listener, false );
  6. } else   if (element.attachEvent) {
  7. element.attachEvent( "on" + eventName, listener);
  8. } else {
  9. element[ "on" + eventName] = listener;
  10. }
  11. },
  12.   
  13. // To remove an event, you cannot use an anonymous function   
  14. removeEventListener: function (element, eventName, listener) {
  15.              if (element.removeEventListener) {
  16. element.removeEventListener(eventName,listener, false );
  17. } else   if (element.detachEvent) { //IE8 previously registered .attachEvent and removed events .detachEvent   
  18. element.detachEvent( "on" +eventName,listener);
  19. } else {
  20. element[ "on" + eventName] = null ;
  21. }
  22. }
  23. };

6. Event Object

1) Event parameter e is the event object, which is obtained in a standard way

btn.onclick = function(e) { }

2) e.eventPhase event phase, not supported before IE8

3) e.target is always the object that triggered the event (the button that was clicked)

i) srcElement before IE8

ii) Browser compatibility

var target = e.target || window.event.srcElement;

JavaScript CodeCopy content to clipboard
  1. // Get the event object compatible with the browser   
  2. getEvent: function (e) {
  3.      return e || window.event; // e event object standard way to obtain; window.event IE8 and before the way to obtain the event object   
  4. }
  5. // compatible with target   
  6. getTarget: function (e) {
  7.      return e.target || e.srcElement;
  8. }

7. Get the mouse position on the page

① Position in the visible area: e.clientX e.clientY

②Position in the document:

i) e.pageX e.pageY

ii) Browser compatibility

JavaScript CodeCopy content to clipboard
  1. var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  2.   
  3. var pageY = e.clientY + scrollTop;

8. Get the page scroll distance

JavaScript CodeCopy content to clipboard
  1. // Compatible browsers   
  2. var scrollTop = document.documentElement.scrollTop || document.body.scrolltop;

9. Deselect text

JavaScript CodeCopy content to clipboard
  1. // Compatible browsers   
  2. window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();

The above brief discussion on browser compatibility issues in JavaScript is all the content that the editor shares with you. I hope it can give you a reference. I also hope that you will support 123WORDPRESS.COM.

<<:  How to display and format json data on html page

>>:  Docker container regularly backs up the database and sends it to the specified mailbox (design idea)

Recommend

Vue virtual Dom to real Dom conversion

There is another tree structure Javascript object...

Comparing the performance of int, char, and varchar in MySQL

There are many seemingly true "rumors" ...

Detailed tutorial of using stimulsoft.reports.js with vue-cli

vue-cli uses stimulsoft.reports.js (nanny-level t...

Detailed tutorial on compiling and installing python3.6 on linux

1. First go to the official website https://www.p...

Solution for converting to inline styles in CSS (css-inline)

Talk about the scene Send Email Embedding HTML in...

Perfect solution to MySQL common insufficient memory startup failure

1. If MySQL is not started successfully, check th...

Detailed graphic tutorial on how to enable remote secure access with Docker

1. Edit the docker.service file vi /usr/lib/syste...

Complete steps to implement location punch-in using MySQL spatial functions

Preface The project requirement is to determine w...

Docker container monitoring and log management implementation process analysis

When the scale of Docker deployment becomes large...

Detailed explanation of the abbreviation of state in react

Preface What is state We all say that React is a ...

Summary of the differences between Html, sHtml and XHtml

For example: <u> This has no ending characte...