1、找到application/function.php添加自定义文章内容输出方法
if (!function_exists(‘lazy_msubstr‘))
{
function lazy_msubstr($content=‘‘) {
if (!empty($content)) {
preg_match_all(‘/<img.*(\/)?>/iUs‘, $content, $imginfo);
$imginfo = !empty($imginfo[0]) ? $imginfo[0] : [];
if (!empty($imginfo)) {
foreach ($imginfo as $key => $imgstr) {
$imgstrNew = $imgstr;
if(false !== strpos($imgstrNew, ‘data-original‘)) {
return $imgstrNew;
}
$mytemplate = \think\Config::get(‘template.view_path‘);
$loading = $mytemplate.‘images/xdunz.jpg‘; //改成你默认显示的图片,可以是gif旋转动画图片,这里是放在模板images文件夹里
//判断img标签是否有class
if (!preg_match(‘/class/i‘, $imgstrNew)) {
$imgstrNew = preg_replace(‘#<img([^>]+?)src=[\‘"]?([^\‘"\s>]+)[\‘"]?([^>]*)>#‘, sprintf(‘<img ${1} class="lazy" src="%s" data-original="${2}" ${3}><noscript><img${1}src="${2}"${3}></noscript>‘, $loading), $imgstrNew);
} else {
$imgstrNew = preg_replace(‘#<img([^>]+?)src=[\‘"]?([^\‘"\s>]+)[\‘"]?([^>]*)>#‘, sprintf(‘<img ${1} src="%s" data-original="${2}" ${3}><noscript><img${1}src="${2}"${3}></noscript>‘, $loading), $imgstrNew);
$imgstrNew = preg_replace(‘/class(\s*)=(\s*)[\‘|\"](.*?)[\‘|\"]/i‘, ‘class="${3} lazy"‘, $imgstrNew);
}
$content = str_ireplace($imgstr, $imgstrNew, $content);
}
}
}
return $content;
}
}
2、前台调用
{$eyou.field.content|lazy_msubstr=###}
3、最后别忘了,引入js插件,并在适当地方初始化插件
比如在公共js文件中写上
$(".lazy").picLazyLoad({ threshold: 200 });
原文:https://blog.51cto.com/14747960/2485814