Created
October 18, 2012 01:54
-
-
Save sofish/3909438 to your computer and use it in GitHub Desktop.
Scroll News
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 完成滚动信息的简短代码 | |
~function ($) { | |
/* 浮动信息插件 | |
* @author sofish, [email protected] | |
* @param options {Object} 加下的参数 | |
* { | |
* data: 传入的 JSON 数据 | |
* tmpl: 显示信息的格式模板 `{json 数组中 object 的 key 名} 发布了 {dataName}` | |
* 为了更快的匹配,{dataName} 中的 dataName 只支持除中文外的 js 变量名命名方法中支持的内容 | |
* interval: [可选] 间隔时间,默认为 3 秒 | |
* } | |
* @example 二手首页的一个例子 | |
* var data = $.evalJSON('xxx'), | |
* tmpl = '{relativeTime} <cite>{nickname}</cite> 发布了 <cite> {title}</cite>'; | |
* | |
* $('.catmsg').scrollNews({ | |
* data: data, | |
* tmpl: tmpl | |
* }); | |
*/ | |
$.fn.scrollNews = function (options) { | |
var ads = options['data'], | |
tmpl = options['tmpl'], | |
interval = options['interval'] || 3000, | |
timer, | |
len = Math.max(ads.length - 1, 0), | |
i = 0, | |
that = this, | |
// 简单的模板解析 | |
renderTmpl = function (item, tmpl) { | |
tmpl.replace(/{\w+}/g, function (match) { | |
tmpl = tmpl.replace(match, item[match.slice(1, - 1)]); | |
}); | |
return tmpl; | |
}, | |
// 显示 view | |
renderView = function () { | |
if (!that.length) return clearInterval(timer); | |
i = i === len ? 0 : i; | |
that.hide(); | |
that.html(renderTmpl(ads[i++], tmpl)); | |
that.slideDown(300); | |
}; | |
if (!ads.length) return; | |
renderView(); | |
timer = setInterval(renderView, interval); | |
} | |
}(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment