简体   繁体   中英

jQuery get the height of each div on a page with a certain class

I have a page with several divs with the class .layers-content-widget . Each div has differing amounts of content, so they differ in size, I want to make them all the same size as the page, regardless of how much content there is (unless of course there is more content than page height) Whilst still having the content sat in the middle of the div.

Here is my jQuery:

var pageHeight = $(window).height();
var sectionInnerHeight = $('.layers-content-widget').innerHeight();
$('.layers-content-widget').css('padding-top', ((pageHeight-sectionInnerHeight)/2));
$('.layers-content-widget').css('padding-bottom', ((pageHeight-sectionInnerHeight)/2));

The idea here is to get the page height and the content height (using innerHeight), divide this number by 2 and add it on as padding to the top and bottom - with the idea that the content will then sit in the middle of a full page section.

The issue I'm having is that this code works for the first div, but then applies the same amount of padding to all the other divs on the page. I know I need to use this but am unsure of how my final code should look

Your code is only running once and applying the calculated padding to each of the divs. What you need to do is parse all the divs in question and apply the padding to each individually...

var pageHeight = $(window).height();
$('.layers-content-widget').each(function() {
    var $this = $(this);
    var sectionInnerHeight = $this.innerHeight();
    $this.css({
        'padding-top': ((pageHeight - sectionInnerHeight) / 2),
        'padding-bottom': ((pageHeight - sectionInnerHeight) / 2)
    });
});

Here's the jQuery documentation for each , which is all you were really missing...

http://api.jquery.com/jquery.each/

.css could be used with second argument as function [ Ref ]

A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

 $('button').on('click', function() { $('div').css('height', function() { var h = $(this).height() / 2; return h; }); }); 
 div { float: left; width: 100px; background: green; border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div style="height:100px">Hello</div> <div style="height:50px">Hello</div> <div style="height:200px">Hello</div> <button>MakeThemHalf</button> 

Fiddle Demo

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