本文介绍了jquery比较img下的高度和h2的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如下所示:





编辑:

所以我只是想知道解决这个问题的最好方法是将高度设置为 h2 标记,并将其内容高度与设置的高度进行比较。

解决方案

像这样的东西可以正常工作:

  $('。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)* $ /,'...');
});
}
});



您应该使用 .block {word-wrap:break-word; } (或者在这些长长的h2文本中加入一些空格)让它们突破并帮助实现效果。



在,这只是一个想法,而不是准备在生产中使用的东西。这是相当DOM重,可能不是所有用例的最佳解决方案。


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

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.

解决方案

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.

这篇关于jquery比较img下的高度和h2的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 02:25