window.innerHeight ie8 alternative

后端 未结 5 1126
再見小時候
再見小時候 2020-12-08 07:53

I have some calculations that rely on window.innerHeight. But as I have found out this is not available in any IE before IE9. All the other options I have look

5条回答
  •  再見小時候
    2020-12-08 08:37

    I made a simple shim for IE8 and others:

    • window.innerWidth
    • window.innerHeight
    • window.scrollX
    • window.scrollY
    • document.width
    • document.height

    559 bytes

    (function(d,b){var c=b.documentElement;var a=b.body;var e=function(g,h,f){if(typeof g[h]==="undefined"){Object.defineProperty(g,h,{get:f})}};e(d,"innerWidth",function(){return c.clientWidth});e(d,"innerHeight",function(){return c.clientHeight});e(d,"scrollX",function(){return d.pageXOffset||c.scrollLeft});e(d,"scrollY",function(){return d.pageYOffset||c.scrollTop});e(b,"width",function(){return Math.max(a.scrollWidth,c.scrollWidth,a.offsetWidth,c.offsetWidth,a.clientWidth,c.clientWidth)});e(b,"height",function(){return Math.max(a.scrollHeight,c.scrollHeight,a.offsetHeight,c.offsetHeight,a.clientHeight,c.clientHeight)});return e}(window,document));
    

    For updates, take a look at this gist: yckart/9128d824c7bdbab2832e

    (function (window, document) {
    
      var html = document.documentElement;
      var body = document.body;
    
      var define = function (object, property, getter) {
        if (typeof object[property] === 'undefined') {
          Object.defineProperty(object, property, { get: getter });
        }
      };
    
      define(window, 'innerWidth', function () { return html.clientWidth });
      define(window, 'innerHeight', function () { return html.clientHeight });
    
      define(window, 'scrollX', function () { return window.pageXOffset || html.scrollLeft });
      define(window, 'scrollY', function () { return window.pageYOffset || html.scrollTop });
    
      define(document, 'width', function () { return Math.max(body.scrollWidth, html.scrollWidth, body.offsetWidth, html.offsetWidth, body.clientWidth, html.clientWidth) });
      define(document, 'height', function () { return Math.max(body.scrollHeight, html.scrollHeight, body.offsetHeight, html.offsetHeight, body.clientHeight, html.clientHeight) });
    
      return define;
    
    }(window, document));
    

提交回复
热议问题