调整窗口大小时更新元素高度

时间:2017-08-03 06:27:32

标签: javascript jquery html css window-resize

我有一个JS代码:

var setPostHeaderHeightsInSlider = function() {
    var titlesHeight = 0;
    var teasersHeight = 0;

    $('.posts-slider .post-item').each(function() {
        var titleHeight = $(this).find('.post .post-header h3').height();
        var teaserHeight = $(this).find('.post .post-header p').height();

        if (titleHeight > titlesHeight) {
            titlesHeight = titleHeight;
            $('.posts-slider .post-item .post .post-header h3').css('height', titlesHeight);
        }

        if (teaserHeight > teasersHeight) {
            teasersHeight = teaserHeight;
            $('.posts-slider .post-item .post .post-header p').css('height', teasersHeight);
        }
    });
};

var onResize = function() {
    console.log('resize');
    setPostHeaderHeightsInSlider();
};

$(document).ready(function () {
    onResize();
    $(window).on('resize', function(){
        onResize();
    });
}

当窗口调整大小但我的代码不起作用时,我需要更新元素的高度。

我在控制台中看到文字,但高度不会更新。

@edit:

我把我的HTML代码。

HTML:

<div class="posts-slider swiper-container w-100 fl">
    <div class="swiper-wrapper">
        <div class="post-item swiper-slide ph4 pt3">
            <a href="artykul.html" class="w-100 fl">
                <article class="post w-100 fl">
                    <figure class="post-photo w-100 tc fl ma0 relative">
                        <img src="img/post_01.jpg" alt="Post 01" class="dib mw-100">
                    </figure>
                    <header class="post-header w-100 tl fl">
                        <h3 class="ma0 mt3">Lorem ipsum dolor sit amet, consectetur adipisicing elit</h3>
                        <p class="ma0 mt3">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis, itaque, sapiente! Aliquid autem, deserunt dicta dolorum earum eius explicabo incidunt, modi natus temporibus ullam ut vel voluptatum? Libero recusandae, unde?</p>
                     </header>
                     <footer class="post-footer w-100 tl fl">
                          <p class="pv3 ma0 mt4">22 czerwca 2017</p>
                     </footer>
               </article>
          </a>
      </div>
   </div>
 </div>

仅在刷新页面时设置高度。

2 个答案:

答案 0 :(得分:1)

替换这一行,它将适合你

    var titleHeight = $(this).find('.post .post-header h3').removeAttr("style").height();
    var teaserHeight = $(this).find('.post .post-header p').removeAttr("style").height(); 

答案 1 :(得分:0)

请删除ph3来尝试使用该代码 这意味着,
(通过你的代码) $(this).find('.post .post-header').height();而非 $(this).find('.post .post-header p').height();

相关问题