簡體   English   中英

獲取元素的高度,然后添加類/更改css

[英]Get height of element then add class/change css

我正在嘗試獲取div中每個h2的高度,然后,如果該高度大於21px,則對該h2應用一個類或更改其CSS。

原因是當標簽長於一行時,我的項目標題會與標簽重疊:

http://www.elisagilis.be

到目前為止,我已經嘗試過了:

$('.post-details h2').each(function(){
     if($(this).height() > 21)
     {
         $(this).css({"margin-top": "315px", "line-height": "28px"});
     }
 });

和這個 :

$('.post-details h2').each(function(){
    if($(this).height() > 21)
    {
        $(this).addClass('margintop');
    }
});

他們都不工作。 我也嘗試過不使用每一個,但沒有用,因為它將選擇我所有的h2並將css / class應用於所有它們。 -如果您有比我正在考慮的解決方案更好的解決方案,也歡迎他們。

非常感謝您的幫助!

我想這就是你要找的

<h2>some text</h2>
<h2>some text<br>some more</h2>

.border {border:1px solid blue;}

$('h2').each(function(){

    alert($(this).height()); 

    if($(this).height() > 30)
    {
        $(this).addClass('border');
    }
});

只需將其更改為您的首選項即可。

https://jsfiddle.net/370mg7ak/1/

也許這就是您想要的: FIDDLE

HTML

<div class="cta">
    <span class="cta-title">one line</span>
</div>
<div class="cta">
    <span class="cta-title">one line</span>
</div>
<div class="cta">
    <span class="cta-title">this will take up two lines</span>
</div>

CSS

.cta { width: 100px; float: left; height: 100px; border: 1px solid black; }
.cta-title { width: 100%; color: white; background: black; display: inline-block; }
.two-line { background-color: red; }

jQuery的

$(document).ready(function() {
$(function(){
  var $tArray = $('div.cta').children('span');
  $tArray.each(function(){
    if ($(this).height() > 18) {
        $(this).addClass('two-line');
    }
  });
});
    });

為了使值隨着窗口調整大小而動態變化,請嘗試以下操作:

$(window).on("resize", ".post-details h2", function(){
    if($(this).height() > 21)
    {
        $(this).addClass('margintop');
    }
});

這將附加到windowonresize事件,並根據".post-details h2"選擇器過濾事件。 但是,在這種情況下,您可能還必須考慮頁面大小是否再次變大,然后還需要使用初始化情況。

//Initial setup
$(".post-details h2").each(function(){
    if($(this).height() > 21)
        $(this).addClass('margintop');
});

//On window resize
$(window).on("resize", ".post-details h2", function(){
    if($(this).height() > 21)
        $(this).addClass('margintop');
    else
        $(this).removeClass('margintop');
});

我可能會刪除position:absolute; <p>標簽開始,讓元素自然流動。 這樣,您就不必擔心維護任何額外的javascript。

要獲得底部的20px填充,可以添加以下樣式:

.post-details > a, .post-details p { transform: translateY(-20px); }

替換以下代碼

$('.post-details h2').each(function(){
  if($(this).height() > 21)
  {
    $(this).css({"margin-top": "315px", "line-height": "28px"});
  }
});

$(function(){    
  $('.post-details h2').each(function(){
    if($(this).height() > 21)
    {
      $(this).css({"margin-top": "315px", "line-height": "28px"});
    }
  });
});

我最終將我的元素分組到僅使用CSS定位的單個div中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM