jquery compare the height beneath img to h2's height

好久不见. 提交于 2019-12-11 08:18:49

问题


I am trying to adapt this:

var h2=$('.block h2');
var divh=$('.block').height();
while ($(h2).outerHeight()>divh) {
    alert('enters while');
    $(h2).text(function (index, text) {
        return text.replace(/\W*\s(\S)*$/, '...');
    });
}

as explained here: Cross browsers mult-lines text overflow with ellipsis appended within a width&height fixed div?

The problem I have encountered in my case is that I have various li where each one contains a .block which has a h2 tag per li

Example:

<li>
<div class="block">
....
<h2>Tittleasfasjgpashgj9ahgpasgnapsighapighapsogna</h2>
...
</div>
</li>

<li>
<div class="block">
....
<h2>5Tittleasfasjgpashgj9ahgpasgnapsighapighapsogna</h2>
...

http://i.stack.imgur.com/lI82f.jpg

Having .block set with 200px, inside having img set to height: 90px; and a padding: 5px now I need to take the height left beneath img and compare to h2's height.

But it doesn't work either, it just doesn't do the if, but divh contains data (200, the 200px set in css).

Edit:

So I just figure out that the best way to fix this is to set a height to h2 tag and than compare its content height with the set one.


回答1:


Something like this would work fine:

$('.block').each(function (i, el) {
    var $h2 = $(el).find('h2');
    var divh = $(el).height();
    while ($h2.outerHeight() > divh) {
        $h2.text(function (index, text) {
           return text.replace(/\W*\s(\S)*$/, '...');
        });
    }
});

jsFiddle Demo

You should use .block { word-wrap: break-word; } (or put some spaces into those long h2 texts) to let them break and help the effect happen.

As I also stated in the original question, this is just an idea, not something ready to be used in production. It is quite DOM-heavy and may not be the best solution for all use cases.




回答2:


First of all, you're regex only works for space separated words. Long strings like you have won't be shortened.

Secondly, you dont need to use another selector on your h2 var in the while condition.

Thirdly, the .each is definitely required.

var h2=$('.block h2');
h2.each(function(){
    var divh=$(this).closest('.block').height();
    while ($(this).outerHeight()>divh) {
        $(h2).text(function (index, text) {
            return text.replace(/\W*\s(\S)*$/, '...');
        });
    }
});

jsfiddle link




回答3:


I think you may have a couple of problems, first you have a typo on the "while" line where I think you really want to do

while ($('h2').outerHeight()>divh) {

But really I think you want to use the .each() jquery method, something like

$('h2').each(function(i) {
  if ($(this).outerHeight() > divh) {
    //...
  }
});


来源:https://stackoverflow.com/questions/9088566/jquery-compare-the-height-beneath-img-to-h2s-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!