WordPress自动截断字符的几种方法。

1.PHP方法

<?php

echo mb_strimwidth(//调用mb_string的extension方法

strip_tags(//过滤字符中的源代码

apply_filters(’the_content’, $post->post_content)//过滤截取的内容。

),

0, 80,"…");//80是字符长度,另外这边可以设定强制编码。

?>

优点:简单有效,通用性强。

缺点:服务器必须开启PHP的mb_string模块。

其他的PHP截断字符的方法都需要写函数,比较麻烦,这里就不多说了。

2.jQuery方法。

$(document).ready(function(){

$("[@limit]").each(function(){
var Text = $(this).text();//获得内容,这里会过滤小HTML代码
var textLength = $(this).text().length;//得到内容字节数
var num = $(this).attr("limit");//获得需要截取的值
//alert(textLength)
if(textLength > num){
$(this).attr("title",Text);//将完整内容写入标签Title,有利于客户体验。
$(this).text(Text.substring(0,num) + "…");//…是结尾最加的东西
}
});

});

<h2 limit="24">截取内容截取内容截取内容截取内容截取内容截取内容截取内容截取内容</h2>

优点:通用性强,有利于SEO。

缺点:稍微有点难,另外当前页面需要截取的内容过多的话可能对客户端造成压力。

3.CSS方法。

h2.title{
width:200px; // 宽度
height:24px; // 高度
overflow:hidden; // 裁切超出部分
text-overflow:ellipsis; // 显示省略号,Firefox无效。
white-space:nowrap; // 强制不换行 。
}

优点:简单。

缺点:通用性差。

Comments [6] TAG: , , , , , | Categories: Web 技术

Posted on: 十二月 26, 2008

SEARCH

A Bit About Me

喜欢胡思乱想。兴趣极为广泛,并为此烦恼。
{CSSWORK}是我的个人网志,记录了一些生活中的琐事、工作的新得MORE +

本站采用: Creative Commons 协议