Home  >  Article  >  Web Front-end  >  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)?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 18:40:03866browse

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:

<code class="javascript">/* 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:**
</code>

$('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**

The above is the detailed content of Is there a cross-browser JavaScript alternative to CSS viewport units (vh and vw)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn