我有一个使用 PHP 和 MySQL 显示的带有文本的 div,结构是这样的:
<div class="description">
<p>
Here is a lot of text.
</p>
</div>
当 p 标签内的文本超过 100 个字符时,我想显示“阅读更多”链接。我可以像这样用 PHP 显示“阅读更多”链接:
// 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 或其他东西?
最佳答案
如果您想在不重新加载页面的情况下显示全文,您将不得不使用 javascript/jquery。为此,全文必须包含在生成的 HTML 中。
我通过使用 2 个 div
来做到这一点,一个包含缩短的文本,一个包含默认隐藏的全文。单击“阅读更多”时,我切换两个 div
并将链接标签更改为“少看”。
您还可以像这样将未缩短的文本和省略号放在元素中:
<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>
参见 this fiddle .
关于javascript - div限制字符的文本,添加 "Read more"链接,点击链接显示所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23170581/