"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Is there a cross-browser JavaScript alternative to CSS viewport units (vh and vw)?

Is there a cross-browser JavaScript alternative to CSS viewport units (vh and vw)?

Published on 2024-11-15
Browse:788

Is there a cross-browser JavaScript alternative to CSS viewport units (vh and vw)?

CSS Viewport Units with JavaScript

CSS3 introduces viewport-percentage length units, vh and vw, which are valuable for responsive layouts. However, the question arises of whether there exists a cross-browser JavaScript alternative for these units.

JavaScript/jQuery Alternative

Absolutely! jQuery can be leveraged to provide an alternative for viewport units. Here's a jQuery-based solution:

/* jQuery plugin to convert viewport units to pixels */
;(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
      , originalArguments = arguments
      , update = function() {
          if ( typeof props === 'string' || props instanceof String ) {
            if (originalArguments.length > 1) {
              var argumentsObject = {};
              argumentsObject[originalArguments[0]] = originalArguments[1];
              return _css.call(self, parseProps($.extend({}, argumentsObject)));
            } else {
              return _css.call( self, props );
            }
          } else {
            return _css.call( self, parseProps( $.extend( {}, props ) ) );
          }
        };
    $win.resize( update ).resize();
    return update();
  };

}( jQuery, window ));

**Usage:**

$('div').css({
height: '50vh',
width: '50vw',
marginTop: '25vh',
marginLeft: '25vw',
fontSize: '10vw'
});

This solution seamlessly integrates the viewport unit conversion into jQuery's CSS method, allowing for easy resizing of elements based on viewport dimensions.

**Safety Considerations**
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3