时间:2021-07-01 10:21:17 帮助过:13人阅读
先给大家展示下效果图:
完整demo如下
每两秒随机向上或者向下滚动,如果要替换新内容,则通过html()更新内容即可(查看注释代码)
<!DOCTYPE html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style> ul,li{ list-style-type:none; border: solid; } ul{ overflow: hidden;/*让li超出ul时隐藏*/ } body{ margin: 0px; } </style> </head> <body> <div> <ul> <li> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1503543418892&di=1f606f0990cf6fa893c8330457b5fde2&imgtype=0&src=http%3A%2F%2Fi3.hoopchina.com.cn%2Fblogfile%2F201509%2F16%2FBbsImg144240668814516_480*360.jpg"/> </li> <li><img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1503543451619&di=a578daa6b6f794cb233f655cd5ecaf91&imgtype=0&src=http%3A%2F%2Fimg.qqzhi.com%2Fupload%2Fimg_0_3518803618D2241430362_23.jpg"/> </li> <li><img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1503544550636&di=086d271111b428fadf9e23abb7c06b1e&imgtype=0&src=http%3A%2F%2Fuploads.yeyoujia.com%2Fcms%2Fimages%2F2017%2F02%2F10%2F589d8e4598d46285900450.png"> </li> </ul> </div> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script> <script> function getRandom(min, max){ var r = Math.random() * (max - min); var re = Math.round(r + min); re = Math.max(Math.min(re, max), min) return re; } $(function(){ setInterval(function(){ if(getRandom(0,1)==0){ //向上滚动特效 var ul = $("ul"); var $first = ul.find('li:first'); var height = $first.height(); $first.animate({ marginTop: -height + 'px' }, 500, function() { // $first.css('marginTop', 0).html(new Date().getMinutes()+":"+new Date().getSeconds()).appendTo(ul);/*不要写成append*/ $first.css('marginTop', 0).appendTo(ul); }); }else{ //向下滚 var ul = $("ul"); var liHeight = ul.find("li:last").height();//计算最后一个li元素的高度 ul.animate({marginTop : liHeight +"px"},500,function(){ // ul.find("li:last").html(new Date().getMinutes()+":"+new Date().getSeconds()).prependTo(ul);/*不要写成prepend*/ ul.find("li:last").prependTo(ul);/*不要写成prepend*/ ul.find("li:first").hide(); ul.css({marginTop:0}); ul.find("li:first").fadeIn(1000); }); } },2000); }); </script> </body> </html>
效果