总结下开发经验:
1、当图片不存在时显示默认图片.
<img src="1.gif" border="0" ōnerror="this.src='2.gif'" />
说明:当<img src="1.gif"图片显示错误的时候,将会被 2.gif所代替,这样就不会在出现当图片显示错误时候出现一个叉。
关键: ōnerror="this.src='2.gif'"
2、在文本里找出图片并设定其大小。
说明:在输入文章的时候经常会输入一些图片,也就是图文混合,有的时候图片有可能是很大的图片,会把页面也撑的很大所以要改变文本中图片的大小.
代码:
//$str是文本内容
function controimg($str) {
$str = preg_replace("/onload=[\"|\'].+[\"|\']/i", "", $str);
preg_match("/src=\"[^\"]+/i", $str, $imgs);
$imgs = substr($imgs[0], 5, strlen($imgs[0]));
if(preg_match ("/<img[^>]+>/i", $str)) {
$str = preg_replace("/<img([^>]+>)/i","<img ōnload=\"if(this.width>490){this.width=490,this.style.cursor='hand'; this.alt='点击查看大图'; this.title='点击查看大图';}\" border=\"0\" ōnmouseover=\"if(this.width>=490) {this.resized=true; this.width=490; this.style.cursor='hand'; this.alt='点击查看大图'; this.title='点击查看大图';}\" ōnclick=\"if(!this.resized) {return true;}else { window.open('{$imgs}')}\" $1", $str);
}
return $str;
}
1、把文本中onload事件全部替换成空(这么做也许会误删,期待更好的方法) $str = preg_replace("/onload=[\"|\'].+[\"|\']/i", "", $str); 。
2、匹配字符src=" 字符目的就是看看有没有图片,如果有的话保存到$imgs数组里。preg_match("/src=\"[^\"]+/i", $str, $imgs);。
3、匹配img标签,把img标签替换成<img ōnload=\"if(this.width>490){this.width=490,this.style.cursor='hand'; this.title='点击查看大图';}\" border=\"0\" ōnmouseover=\"if(this.width>=490) {this.resized=true; this.width=490; this.style.cursor='hand'; this.alt='点击查看大图'; this.title='点击查看大图';}\" ōnclick=\"if(!this.resized) {return true;}else { window.open('{$imgs}')}\" $1", $str);
意思是在img里加入onload事件,如果图片的宽大于490就把图片的宽设为490并把鼠标样式改成小手,当鼠标放上去显示‘点击查看大图’,当鼠标放上去的时候触发onmouseover事件,如果图片的宽大于490就把图片的宽设为490并把鼠标样式改成小手,并设置一个resized来标记图片是否大于490,最后添加个onclick事件,如果图片是大于490的可以点击看大图。
这种方法不是很好!有更好方法的朋友请告诉我!呵呵..
4、给文本中的<a>标签加上target="_blank"
//$str为文本内容
function add_href_blank($str) {
$str = preg_replace ("/target=([_a-zA-Z]+)/i","",$str);
$str = preg_replace("/<a([^>]+)>/i","<a target=_blank $1 >", $str);
return $str;
}
说明:先把文本中所有的target 替换为空。 $str = preg_replace ("/target=([_a-zA-Z]+)/i","",$str);。再把a标签替换成<a target=_blank ……. $str = preg_replace("/<a([^>]+)>/i","<a target=_blank $1 >", $str);. 这样就OK啦。