javascriptcssinternet-explorer-7polyfillsviewport-units

Getting polyfill "vminpoly" working with internal CSS


On Saabi's github for vminpoly, a vw and vh unit polyfill (https://github.com/saabi/vminpoly), it says:

Only linked stylesheets are being parsed right now but it's very easy to also parse 'style' elements.

How would vw and vh CSS inside style elements work with vminpoly?


Solution

  • You could refer to the code below to support vh, vw in particular:

    (function($, window) {
    
      var $win = $(window),
        _css = $.fn.css;
    
      function viewportToPixel(val) {
        var percent = val.match(/\d+/)[0] / 100,
          unit = val.match(/[vwh]+/)[0];
        return (unit == 'vh' ? $win.height() : $win.width()) * percent + 'px';
      }
    
      function parseProps(props) {
        var p, prop;
        for (p in props) {
          prop = props[p];
          if (/[vwh]$/.test(prop)) {
            props[p] = viewportToPixel(prop);
          }
        }
        return props;
      }
    
      $.fn.css = function(props) {
        var self = this,
          update = function() {
            return _css.call(self, parseProps($.extend({}, props)));
          };
        $win.resize(update);
        return update();
      };
    
    }(jQuery, window));
    
    //Usage:
    $('div').css({
      height: '50vh',
      width: '50vw',
      marginTop: '25vh',
      marginLeft: '25vw',
      fontSize: '10vw'
    });
    body {
      margin: 0;
    }
    
    div {
      background: #fa7098;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>hello</div>

    The result in IE is like this:

    enter image description here