简体   繁体   中英

Set height to element dynamically and change height on window resizes using jQuery

I am working on a project where I need to set the height dynamically, means when the page loads the height must be set to itself and it's a responsive box, so when the browser window resizes the height increases but I am unable to fix it. I shared the script below. It's not something to calculate with window height or else, it should set and change the height based on window resizes. Any help?

<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
var itemHeight = $('.item').height();
$('.item').each(function() {
  $(this).css({
    height: itemHeight + 'px'
  });
});

$(window).on('resize', function(event) {

  $('.item').each(function() {
    $(this).css({
      height: itemHeight + 'px'
    });
  });
});

Please see the jsfiddle: https://jsfiddle.net/rj1xy1ue/

I will suggest you to use % instead of px . px will fix the value, but % will automatically compute the values based on the available viewport.

var itemHeight = 20; //Sample value
$('.item').each(function () {
    $(this).css({
        height: itemHeight + '%'
    });
});

Simply, find the perfect value of itemHeight which is ideal for your case and then assign it. No need for extra resize event handler.

In your current code, in resize event you are assigning same value again which doesn't make any difference to the dimension. Hence you are not able to see the difference on resize.

Try this:

var itemHeight = $('.item').height();

function resizer() {
    $('.item').each(function () {
        $(this).css({
            height: itemHeight + 'px'
        });
    });
}
$(window).on('resize', function (event) {
    itemHeight = 350 //any different value
    resizer();
});

Sample Demo: http://jsfiddle.net/lotusgodkk/GCu2D/822/

Note: Make sure you change the value of itemHeight in resize handler

What you are describing is called Responsive design.

A key idea in responsive design is to use percentages in place of px.

See these references:

WebDesignerWall on Responsive Design

CSS-Tricks question

for some ideas.

Note that using percentages for height is not as important as for width. You might also want to check out

Responsive Layouts with flexbox


On the jQuery side, you can use something like this:

var win = $(window);

$(function() {

    win_size_recalc();

    $(window).on('resize', function(){
        win_size_recalc();
    });

}); //end document.ready

function win_size_recalc(){
    ww = win.width();

    //EXAMPLE OF USE:
    if (ww <= 550){
        $('#header').css({'height':'50px'});
        $('nav').css({'height':'55px'});
        $('#headerstuff').css({'width':'98%'});
    }else if (ww <= 650){
        $('#headerstuff').css({'width':'98%'});
        $('nav').css({'width':'98%'});
    }else if (ww <= 770){
        $('#headerstuff').css({'width':'90%'});
        $('nav').css({'width':'90%'});
    }else if (ww <= 850){
        $('#headerstuff').css({'width':'90%'});
        $('nav').css({'width':'90%'});
    }else if (ww <= 900){
        //etc etc
}

You might also want to check out CSS media queries, which is the CSS way of doing what we just did above using jQuery:

https://css-tricks.com/css-media-queries/

https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

and more

As others have noted, the main problem is you're only calculating itemHeight once. This fiddle shows a more modern way to use jQuery to achieve your goals (use on instead of bind ):

http://jsfiddle.net/sean9999/7j4sz3wv/6/

 $(function(){ "use strict"; var resizeBoxes = function(){ var padding = 25; var parentHeight = $('body').height() - padding; $('#debug').html( 'parent height = ' + parentHeight ); $('.item').css('height',parentHeight); }; $(window).on('resize',resizeBoxes); resizeBoxes(); }); 
 body { position: absolute; height: 100%; width: 100%; margin: 0; padding: 0; background-color: #FED; } #debug { width: 50%; float: right; height: 100%; margin-top: 25%; font-weight: bold; color: navy; } .item { min-width: 25px; border: 2px solid blue; background-color: silver; min-height: 100px; float: left; margin: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div id="debug"></div> 

I am not sure if I am able to understand your question correctly but I'll give a try based on what I could understand anyway.

You want the .item objects to resize on resize event of window object such that you want to start with whatever .height() these .item objects have, and then scale proportionally to the window height on resize .

If this is what you wanted, the solution is pretty simple. You calculate the difference in .height() of window object, and you add (or remove) that difference to the default .height() of .item objects.

Take a look at this jsFiddle and resize the height of the result panel to observe the difference in height of the .item objects. And tell me if this is what you were expecting the result to be.

The JavaScript used in the example is as below:

var items = $('.item');
var windowObject = $(window);
var defaultWinHeight = windowObject.height();
var defaultItemHeight = items.height();
items.css({ height: defaultItemHeight + 'px' });
windowObject.on('resize', function (event) {
    var currWinHeight = windowObject.height();
    var difference = currWinHeight - defaultWinHeight;
    var itemHeight = defaultItemHeight + difference;
    items.css({ height: itemHeight + 'px' });
});

Apologies if this is not what you were looking for. Hope it helps in some way though.

Update #1:

And here is another resulting jsFiddle of the same experiment but involving calculating percentages.

JavaScript:

var items = $('.item');
var windowObject = $(window);
var defaultWinHeight = windowObject.height();
var defaultItemHeight = items.height();
items.css({ height: defaultItemHeight + 'px' });
windowObject.on('resize', function (event) {
    var currWinHeight = windowObject.height();
    var currWinPercent = (currWinHeight/defaultWinHeight)*100;
    var itemHeight = (currWinPercent/100)*defaultItemHeight;
    items.css({ height: itemHeight + 'px' });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM