[英]Expand the div to “read more”
我在我的網站上遇到了一個問題,我正在尋找解決方案。 帖子是從MySQL數據庫中提取的。 如果它包含幾行,則會完全顯示。但是,如果它包含太多行(從而在瀏覽器屏幕上占用更多空間),那么我希望它顯示為單行后跟點(例如,您的太長的帖子....)通過點擊顯示整個帖子的“看到更多”選項(如在facebook,twitter等中所見)。 它是javascript或jquery的客戶端解決方案,還是PHP可以在服務器端處理的。 非常感謝您的建議!
整個帖子都是從MySQL獲取的,我直接回應它:
<?php
//code
while($row=mysql_fetch_array($result))
{
echo $row['posts'];
}
?>
此時我只是從數據庫中獲取整個帖子並回顯它。我想在這里使用javascript解決方案來完成剩下的工作。
你可以用jquery做到: -
<div class="columns">
your text goes here. Try long text here....
</div>
a.morelink {
text-decoration: none;
outline: none;
}
.morecontent span {
display: none;
}
.comment {
width: 400px;
background-color: #f0f0f0;
margin: 10px;
}
<script>
var showChar = 120;
var ellipsestext = "...";
var moretext = "more";
var lesstext = "less";
$(".columns").each(function () {
var content = $(this).html();
if (content.length > showChar) {
var first = content.substr(0, showChar);
var second = content.substr(showChar - 1, content.length - showChar);
var html = first + '<span class="moreellipses">' + ellipsestext+ ' </span><span class="morecontent"><span>' + second + '</span> <a href="" class="morelink">' + moretext + '</a></span>';
$(this).html(html);
}
});
$(".morelink").click(function(){
if($(this).hasClass("less")) {
$(this).removeClass("less");
$(this).html(moretext);
} else {
$(this).addClass("less");
$(this).html(lesstext);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});
</script>
HTML和PHP :
<?php
$text = '. . .';
$limit = 100;
?>
<div class="text">
<?php
if (strlen($text) < $limit) {
echo $text;
} else {
echo substr($text, 0 , $limit);
echo "<br/><a href='#' onclick='showMore()'>read more</a>";
}
?>
</div>
jQuery :
<script>
function showMore() {
var text = '<?php echo $text; ?>'
$(".text").html(text);
}
</script>
你可以試試這個。
<?php
$str = 'simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's';
$limit = 40;
if(strlen($str)>$limit){
$stringCut = substr($str, 0, $limit);
$serRpos = strrpos($stringCut, ' ');
$first_part = substr(substr($str, 0, $limit), 0,$serRpos);
$last_part = substr($str,$serRpos);
echo $first_part;
echo '<span style="cursor: pointer" onclick="showText(this)"> ...<span class="hide-text" style="display: none;">'.$last_part.'</span></span>';
}
else{
echo $str;
}
?>
和腳本(我使用jquery)
<script type="text/javascript">
function showText(e){
$(e).html($(e).find('.hide-text').html());
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.