显示“更多"基于div中的行数的按钮 [英] Display "Read More" Button based on number of lines in a div

查看:62
本文介绍了显示“更多"基于div中的行数的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有视频说明的视频页面. 现在,我想默认以两行显示说明,说明下方将是阅读更多"按钮.

I have a video page with video description. Now I want to show description with 2 lines by default and below the description will be a 'Read More' button.

但是,如果说明少于或等于2行,则我不想显示阅读更多"按钮.仅当说明超过两行时,才会显示阅读更多"按钮.

But if the description is less than or equal to 2 lines, I don't want to show the 'Read More' button. 'Read More' button will be shown only when description will be more than 2 lines.

我需要使用JS或jQuery完全完成此操作.

I need this to be done completely with JS or jQuery.

这是我迄今为止没有尝试过的尝试.

Here is what I have tried so far with no luck.

<div class="video-description" style="line-height:1.2em;max-height:4.8em;">              
<p>
 Description Line 1
 Description Line 2
 Description Line 3
</p>        
</div>
<div class="read-more-button">Read More</div>

if ($('.video-description').css('height') <= '67px' {
   $('.read-more-button').hide();
} else {
   $('.read-more-button').show();
}

推荐答案

通常没有简单的方法来检测div中有多少行文本...唯一可靠的方法是创建不可见的文本(使用visibility:hidden)具有1和2行的div,以这种方式获得给定类的div中的行的高度. em的问题在于,没有其他方法可以获取em中元素的高度.

Generally there is no simple way to detect how many lines of text are in div... the only reliable way would be to create invisible (with visibility:hidden) divs with 1 and 2 lines and that way to get height of line in div of given class. The problem with em is that there is no other way to get the height of the element in em as well.

当您是新手时,我将简单地解决您的问题以及您的示例为何不起作用...首先,获取元素高度的方式是错误的...如果未设置height样式,它不会返回任何内容,如果设置了样式,它将返回以单位为字符串的值,然后您就不能将其与数字进行比较了.第二件事是,您在if条件中缺少结尾括号()),因此您基本上遇到了语法错误.

As you are new, I will simply address your problem and why your example does not work... First of all, the way of getting element height is wrong... if there would be no height style set, it would return nothing, if style would be set, it would return value with units as a string and then You can't compare it as numbers. Second thing is that you are missing ending bracket ()) in your if condition, so you basically got syntax error.

您应该改用height()和一个以像素为单位的数字进行比较,例如:

You should use height() instead and a number in pixels to compare, for example:

if($('.video-description').height() <= 67){
   $('.read-more-button').hide();
} else {
   $('.read-more-button').show();
}

这篇关于显示“更多"基于div中的行数的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆