jQuery check if browser support position: fixed

后端 未结 7 621
灰色年华
灰色年华 2021-01-04 09:13

How do I check if browser supports position:fixed using jQuery. I assume I have to use $.support I think, but how?

Thank you for your time.

7条回答
  •  执笔经年
    2021-01-04 09:44

    I find that mobile safari (specifically iOS 4.2 via the iOS Simulator on OSX) refuses to scroll anywhere unless you wait a few miliseconds. Hence the false positive.

    I wrote a quick jquery plugin to work around it:

    (function($) {
      $.support.fixedPosition = function (callback) {
        setTimeout(
          function () {
            var container = document.body;
            if (document.createElement && container && container.appendChild && container.removeChild) {
              var el = document.createElement('div');
              if (!el.getBoundingClientRect) return null;
              el.innerHTML = 'x';
              el.style.cssText = 'position:fixed;top:100px;';
              container.appendChild(el);
              var originalHeight = container.style.height,
                  originalScrollTop = container.scrollTop;
              container.style.height = '3000px';
              container.scrollTop = 500;
              var elementTop = el.getBoundingClientRect().top;
              container.style.height = originalHeight;
              var isSupported = !!(elementTop === 100);
              container.removeChild(el);
              container.scrollTop = originalScrollTop;
              callback(isSupported);
            }
            else {
              callback(null);
            }
          }, 
          20
        );
      }
    })(jQuery);
    

提交回复
热议问题