div限制字符中的文字,添加"阅读更多"链接并在单击链接时显示所有字符

时间:2014-04-19 13:22:20

标签: javascript php jquery html limit

我使用PHP&amp ;;显示内部带有文本的div MySQL,结构是这样的:

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

我想要显示一个&#34;阅读更多&#34;当p-tag内的文本超过100个字符时链接。我可以显示&#34;阅读更多&#34;像这样链接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或其他东西?

2 个答案:

答案 0 :(得分:3)

如果要在没有页面重新加载的情况下显示全文,则必须使用javascript / jquery。要使其工作,全文必须在生成的HTML中。

我通过使用2 div来完成此操作,其中一个使用缩短的文本,另一个使用默认隐藏的全文。什么时候阅读更多&#39;单击我切换div两个并将链接标签更改为&#39;少看&#39;。

您还可以将未缩短的文本和省略号放在如下的元素中:

<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

答案 1 :(得分:3)

你可以这样做

<script type="text/javascript">
$(document).ready(function(){
    var maxLength = 300;
    $(".show-read-more").each(function(){
        var myStr = $(this).text();
        if($.trim(myStr).length > maxLength){
            var newStr = myStr.substring(0, maxLength);
            var removedStr = myStr.substring(maxLength, $.trim(myStr).length);
            $(this).empty().html(newStr);
            $(this).append(' <a href="javascript:void(0);" class="read-more">read more...</a>');
            $(this).append('<span class="more-text">' + removedStr + '</span>');
        }
    });
    $(".read-more").click(function(){
        $(this).siblings(".more-text").contents().unwrap();
        $(this).remove();
    });
});
</script>
<style type="text/css">
    .show-read-more .more-text{
        display: none;
    }
</style>
<div class="show-read-more">
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur,  from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.</div>

请参阅此链接Show read more link if the text exceeds a certain length using jQuery

希望这就是你要找的东西。