我正在使用instafeed.js插件动态生成照片Feed。 我想将照片评论截断为140个字符左右,但我遇到了问题。我通过instafeed脚本生成我的标记,它将照片注释放入带有“instacomments”类的div中。我已经编写了另一个函数来尝试使用instacomments类截断任何元素中的字符串,但它不起作用。
Instafeed脚本:
window.onload = function pullPhotos(){
var routeFeed = new Instafeed({
get: 'tagged',
tagName: 'Route91Harvest',
clientId: 'myID',
limit: '18',
resolution: 'low_resolution',
template: '<div class="col-md-4 instapad"><div class="instacontainer heightlimit"><div class="row"><div class="col-md-12 imageblock whitebg"><a href="{{link}}"><img src="http:{{image}}" class="img-responsive center-block" /></a></div></div><div class="row"><div class="col-md-12 whitebg"><div class="instacomments center-block">{{caption}}</div></div></div></div></div>'
});
var rtFeed = new Instafeed({
get: 'tagged',
tagName: 'Rt91Harvest',
clientId: 'myID',
limit: '18',
resolution: 'low_resolution',
template: '<div class="col-md-4 instapad"><div class="instacontainer heightlimit"><div class="row"><div class="col-md-12 imageblock whitebg"><a href="{{link}}"><img src="http:{{image}}" class="img-responsive center-block" /></a></div></div><div class="row"><div class="col-md-12 whitebg"><div class="instacomments center-block">{{caption}}</div></div></div></div></div>'
});
routeFeed.run();
rtFeed.run();
}
这是我的截断脚本,目前无效:
function short(length) {
var s = document.getElementsByClassName('instacomments');
var len = s.length;
for(var i = 0; i < len; i++) {
var g = s[i].innerHTML;
var x = ". . . More";
var leng = length-5;
var html = g.substring(0, leng)+"";
var allHTML = html+x;
s[i].innerHTML = allHTML;
}
}
short(140);
非常感谢任何帮助!
答案 0 :(得分:0)
我会将截断逻辑分开,以便它可以更通用
function trunc(str, max_length, suffix, margin) {
max_length = max_length | 0;
margin = margin | 0;
if (max_length <= 0 || str.length <= max_length + margin)
return str;
if (undefined === suffix || null === suffix)
suffix = '';
return str.slice(0, max_length) + suffix;
}
然后像这样循环
function short(length) {
var s = document.getElementsByClassName('instacomments');
var i = s.length;
while (i--) {
s[i].innerHTML = trunc(s[i].innerHTML, length - 5, ". . . More", 5);
}
}
short(140);
示例演示 function trunc
的参数
trunc('12345' , 5, '…', 0); // "12345"
trunc('123456' , 5, '…', 0); // "12345…"
trunc('123456' , 5, '…', 1); // "123456"
trunc('1234567', 5, '…', 1); // "12345…"