以div限制字符显示的文本,添加“阅读更多内容"链接并在单击链接时显示所有字符 [英] Text in div limited characters, add "Read more" link and show all characters when link is clicked

查看:64
本文介绍了以div限制字符显示的文本,添加“阅读更多内容"链接并在单击链接时显示所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,其中包含使用PHP&MySQL,结构是这样的:

I've a div with text inside that is displayed using PHP & MySQL, the structure is like this:

<div class="description">
    <p>
    Here is a lot of text.
    </p>
</div>

当p标签内的文本超过100个字符时,我想显示更多"链接.我可以像这样用PHP显示更多内容"链接:

I want to display a "Read more" link when the text inside the p-tag is more than 100 characters. I can display the "Read more" link with PHP like this:

// strip tags to avoid breaking any html
$string = strip_tags($string);

if (strlen($string) > 100) {

    // truncate string
    $stringCut = substr($string, 0, 100);

    // make sure it ends in a word so assassinate doesn't become ass...
    $string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... <a href="/this/story">Read More</a>'; 
}
echo $string;

问题是当单击链接时,我想在同一DIV中显示所有文本.PHP可以做到这一点吗?还是我需要jQuery之类的东西?

The problem is that when the link is clicked I want to show all of the text in the same DIV. Is this possible with PHP or do I need jQuery or something?

推荐答案

如果要显示全文而不重新加载页面,则必须使用javascript/jquery.为此,全文必须在生成的HTML中.

If you want to show the full text without a page reload you will have to use javascript/jquery. For that to work the full text has to be in the generated HTML.

我通过使用2个 div 来做到这一点,一个带有缩短的文本,另一个带有全文本默认情况下是隐藏的.单击更多"后,我将同时切换两个 div s并将链接标签更改为少看".

I did this by using 2 divs, one with the shortened text and one with the full text which is hidden by default. When 'read more' is clicked I toggle both divs and change the link label to something like 'see less'.

您还可以将未缩短的文本以及省略号放在这样的元素中:

You could also put the not-shortened text as well as the ellipsis in an element like so:

<div class="readmore">
    This is the shortened text<span class="ellipsis">...</span> <span class="moreText">with the full text hidden</span> <a class="more" href="#">read more</a>
</div>

请参见此小提琴.

这篇关于以div限制字符显示的文本,添加“阅读更多内容"链接并在单击链接时显示所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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