您好,欢迎访问一九零五行业门户网

js实现仿微博滚动显示信息的效果_javascript技巧

相信大家空闲的时候都会上上微博,推特等社交网站,每次我登陆微博时,我都会留意一下它有什么变化,小的有一些布局的变化,大的有api接口的改变等。
在首页登陆微博时,我们可以看到一栏“大家正在说”,它滚动显示着当前每个人发送的微博;刚看到这个效果觉得挺有趣的,所以我们将在接下来的文中介绍实现滚动显示微博信息的效果。
我们细细观察了微博的“大家正在说”,它是通过由上往下滚动来实现不断显示微博的,而且每一天新微博都是通过淡入效果显示的。
图1 微博“大家正在说”
1、定义微博插件
接下来,我们将定义一个插件用来获取某话题下的微博,这里我们将使用jquery的扩建功能来定于一个微博的jquery插件
由于jquery提供了一种机制:让用户给核心模块增加自定义的方法和额外的功能;通过这种机制,jquery允许我们创建自定义的插件封装常用的方法,从而提高我们的开发效率。
首先,我们通过定义自执行的函数(iife),然后把jquery对象作为参数传递给该自执行函数,通过建立“$”和jquery的对应关系,这样“$”就不会在其执行范围内被其他库覆盖了。
// defines a jquery plugin.; (function($) { $.fn.weibosearch = function() { // your plugin logic };})(jquery);
上面,我们定义一个自执行函数(iife),并且在它里面定义了一个扩展方法weibosearch()。
由于,微博api 2.0提供了一个接口search/topics来搜索某一话题下的微博,如果请求成功则返回json格式的数据。
图2微博搜索接口参数
通过上图,我们知道微博搜索接口需要提供应用的appkey(非oauth授权方式)和话题关键字(q)。
接下来,我们定义了一个字面量对象defaults,它包含微博接口的url、应用的appkey、话题关键字(q)和单页返回的记录条数(count)等属性,具体定义如下:
// defines weibo defaults type.$.fn.weibosearch.defaults = { url: 'https://api.weibo.com/2/search/topics.json?q=', appkey: '5786724301', numweibo: 15, term: ''};
2、发送跨源请求
我们可以通过发送ajax请求方式来调用微博搜索接口,如果请求成功服务器会给程序返回json格式数据,那么我们需要把返回的数据呈现到页面中。
$.getjsonp = function(s) { // due to cross origin request, so we to use jsonp format. s.datatype = jsonp; $.ajax(s); // figure out what the callback fn is var $script = $(document.getelementsbytagname('head')[0].firstchild); var url = $script.attr('src') || ''; // gets callback function var cb = (url.match(/callback=(\w+)/) || [])[1]; if (!cb) return; // bail var t = 0, cbfn = window[cb]; $script[0].onerror = function(e) { $script.remove(); handleerror(s, {}, error, e); cleartimeout(t); }; if (!s.timeout) return; window[cb] = function(json) { cleartimeout(t); cbfn(json); cbfn = null; }; // gets time out function flag. t = settimeout(function() { $script.remove(); handleerror(s, {}, timeout); if (cbfn) window[cb] = function() { }; }, s.timeout); /** * fix issue: jquery.handleerror is not a function */ function handleerror(s, xhr, msg, e) { s.error && s.error.call(s.context, xhr, msg, e); s.global && $.event.trigger(ajaxerror, [xhr, s, e || msg]); s.complete && s.complete.call(s.context, xhr, e || msg); }};
上面,我们定义了方法getjsonp(),它通过发送ajax请求的方式调用微博api,这时我们需要跨源请求数据,我们可以通过jsonp格式获取跨源数据,由于它允许在服务器端集成script tags返回至客户端,通过javascript callback的形式实现跨域访问。
接下来,我们在方法$.fn.weibosearch()中定义私有方法grabweibos(),它负责调用getjsonp()方法并且获取返回的json数据显示到页面中。
/*** uses ajax request to grab weibos.*/function grabweibos() { var url = opts.url; grabflag = false; grabbing = true; $.getjsonp({ url: url, timeout: 30000, data: { source: opts.appkey, q: opts.term, count: opts.numweibo }, error: function(xhr, status, e) { }, complete: function() { }, success: function(json) { if (json.error) { // can't get results displays error. return; } // iterates weibo results $.each(json.data.statuses, function(i) { // adds data to page. }) } });}
上面,我们定义了grabweibos(),它调用了getjsonp()方法并且在请求成功后把数据显示到页面中。
3、json数据处理
现在,我们基本实现了jquery.weibo.search.js插件,用来搜索某一话题下的微博的功能,由于时间的关系我们已经把界面设计好了,具体的html代码如下:

接下来,我们在页面代码中引用jquery库和自定义微博话题搜索插件jquery.weibo.search.js,具体代码如下:

上面,我们直接引用google提供的jquery库,当然我们也把jquery库下载到本地,然后引入到项目中,接下来我们在head元素中添加调用微博话题搜索插件的代码,具体代码如下:

上面,我们在页面中调用了weibosearch()的默认方法,并且搜索“情人节”话题下的微博。接下来,我们打开chrome中network选项,查看search/topics中的请求包含了source、count、q和callback(回调函数)参数。
图3 ajax请求
由于chrome中的json数据没有换行不便于查看,所以我们在firefox中查看返回的json格式的数据。
图4微博json数据
上面的json数据不便于查看,这里我们使用json viewer格式化微博数据,格式化后的数据如下:
图5格式化的json数据
通过上图,我们发现微博数据包含在try/catch语句中,如果请求成功catch中将为空,反之,返回相应的错误提示信息。
接下来,我们把微博数据提取出来,然后去掉try/catch我们在json viewer中查看微博数据的结构。
图6 微博json数据
通过上图,我们知道返回数据是一个json数组,它的大小是根据我们的请求参数count决定的,而且微博规定每个请求最多返回200条微博。
接下来,我们需要把数据显示到页面中,现在让我们实现success方法吧!具体代码如下:
// gets response data from weibo api.success: function(json) { if (json.data.error) { // can't get data displays error. faileye(json.data.error); return; } // emptys contain with fade out effect. $cont.fadeout('fast', function() { $cont.empty(); // iterates weibo results $.each(json.data.statuses, function(i) { if (!opts.filter.call(opts, this) || this.truncated) return; // skip this weibo, some weibos may be deleted. var $img, $text, w, tweet = opts.formatter(this, opts), $tweet = $(tweet); // weibo data. $tweet.css(opts.css['tweet']); $img = $tweet.find('.weibosearchprofileimg').css(opts.css['img']); $tweet.find('.weibosearchuser').css(opts.css['user']); $tweet.find('.weibosearchtime').css(opts.css['time']); $tweet.find('a').css(opts.css['a']); $tweet.appendto($cont); $text = $tweet.find('.weibosearchtext').css(opts.css['text']); if (opts.avatar) { w = $img.outerwidth() + parseint($tweet.css('paddingleft')); $text.css('paddingleft', w); } }) // loads weibos with fade in effect. $cont.fadein('fast'); // invokes weibo api again. if (json.data.statuses.length 1) ? arguments[1] : new date(); var delta = parseint((relative_to.gettime() - parsed_date) / 1000); delta = delta + (relative_to.gettimezoneoffset() * 60); if (delta < 60) { return 'just now'; } else if (delta < 120) { return 'a minute ago'; } else if (delta < (60 * 60)) { return (parseint(delta / 60)).tostring() + ' minutes ago'; } else if (delta < (120 * 60)) { return 'about an hour ago'; } else if (delta < (24 * 60 * 60)) { return 'about ' + (parseint(delta / 3600)).tostring() + ' hours ago'; } else if (delta < (48 * 60 * 60)) { return '1 day ago'; } else { return (parseint(delta / 86400)).tostring() + ' days ago'; }}
上面,我们定义了方法relativetime(),首先它通过拼接方式转换时间格式为“feb 14, 2013 20:33:30”,然后把datestring转换为date,接着获取当前时间减去微博时间(created_at)计算出相对时间(delta)。
图8 relativetime计算相对时间
5、微博动态效果
上面,我们通过方法relativetime()把微博的时间转换为相对时间,接下来,我们需要实现微博的滚动(animate)和淡入(fadein)效果。
在新浪微博大厅里,我们可以看到“大家正在说”中每条微博由上往下地滚动着,其实要实现该滚动效果我们可以使用jquery的animate()方法,具体实现如下:
/*** weibos rolling from top to bottom*/function weiboin() { if (paused || grabbing) { settimeout(weiboin, 500); return; } // gets last element. var h, $el = $cont.children(':last'), $elfirst = $cont.children(':first'); // gets last weibo item height. h = $el.outerheight(); // animate: increases the first weibo item margin top to 'h'. // then decreases the first weibo item margin top to '0'. $elfirst.animate({ margintop: h }, opts.animinspeed, function() { $elfirst.css({ margintop: 0, opacity: 1 }); /*@cc_on try { el.style.removeattribute('filter'); } // ie cleartype fix catch (smother) { } @*/ // append the last weibo item first. $el.css(opts.css['tweet']).hide().prependto($cont); // fade in display new item. $el.fadein(opts.animinspeed); // loop settimeout(grabflag ? grabweibos : weiboin, opts.timeout); });}
上面,我们定义了weiboin()方法,它实现微博由上往下滚动显示效果,我们通过animate()方法动态地修改div元素的margintop属性。
接着,我们需要把滚动到最后的微博重新插入到当前第一条微博上,然后通过fadein()函数实现微博淡入显示。
现在,我们基本实现了微博“大家正在说”的向下滚动和淡入效果了,我们先用animate()方法修改div元素的margintop属性,然后通过淡入方式显示滚动下来的微博。
也许有人会问:“如果要实现向上滚动和淡出效果呢”?其实,该效果和我们之前实现的效果恰好相反,首先需要淡出隐藏微博,然后向上滚动。
现在,我们已经有实现的思路了,那么接下来让我们实现向上滚动和淡出效果吧!具体实现如下:
/*** weibos rolling from bottom to top.*/function weiboout() { if (paused || grabbing) { settimeout(weiboout, 500); return; } // gets last element. var h, $el = $cont.children(':first'), el = $el[0]; // implements fade out effect. $el.animate(opts.animout, opts.animoutspeed, function() { // gets first weibo item height. h = $el.outerheight(); $el.animate({ margintop: -h }, opts.animinspeed, function() { $el.css({ margintop: 0, opacity: 1 }); /*@cc_on try { el.style.removeattribute('filter'); } // ie cleartype fix catch (smother) { } @*/ // append the last weibo item last. $el.css(opts.css['tweet']).show().appendto($cont); settimeout(grabflag ? grabweibos : weiboout, opts.timeout); }); });}
在weiboout()方法中,我们通过修改$el的opacity属性实现淡出效果,当然我们也可以使用fadeout()方法实现淡出,同样我们使用方法animate()修改margintop属性,不同的是从-h开始变化。
现在,我们已经实现了淡出、淡入以及滚动效果了,接下来我们需要给界面添加css样式让程序更加美观。
// weibo css style in jquery plugin.css:{ // default styling a:{ textdecoration:'none', color:'#3b5998' }, eye:{ width:'40px', height:'40px', position:'absolute', left:'-30px', top:'-20px', border:'none' }, container:{ overflow:'hidden', backgroundcolor:'#eee', height:'100%' }, fail:{ background:'#6cc5c3 url(./images/error_page_small.png) no-repeat 50% 50%', height:'100%', padding:'10px' }, frame:{ border:'10px solid #c2cff1', borderradius:'10px', '-moz-border-radius':'10px', '-webkit-border-radius':'10px' }, tweet:{ padding:'5px 10px', clear:'left' }, img:{ 'float':'left', margin:'5px', width:'48px', height:'48px' }, loading:{ padding:'20px', textalign:'center', color:'#888' }, text:{}, time:{ fontsize:'smaller', color:'#888' }, title:{ backgroundcolor:'#c2cff1', margin:0, padding:'0 0 5px 0', textalign:'center', fontweight:'bold', fontsize:'large', position:'relative' }, titlelink:{ textdecoration:'none', color:'#3b5998' }, user:{ fontweight:'bold' }}然后,我们weibo.serach.style.css文件中添加以下样式,具体定义如下:div.weibo { margin: auto; width: 300px }#weibo1 { height: 300px;}#weibo2 { height: 300px; }body { background-color: white }body, div { font-family: '微软雅黑', helvetica, verdana, arial, sans-serif }body { margin: 20px 0; padding: 0; font-size: small; color: #333 }div {display: block}/* image rounded corner*/.weibosearchprofileimg{ border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px;}table { margin: auto; border-collapse: separate; border-spacing: 25px;}table { border-collapse: collapse;}
图9 程序界面
现在,我们已经实现了微博搜索插件,搜索“情人节”和“元宵节”话题下的微博,通过该插件我们获取了微博信息并且显示到页面中。
以上就是本文的全部内容,希望对大家学习有所帮助。
其它类似信息

推荐信息