查看本章节
查看作业目录
需求说明:
利用自定义动画 animate() 方法,实现某图书网站中“近 7 日畅销榜”中的图书无缝垂直向上滚动特效:当光标移入到图书上时,停止滚动,鼠标移开时,继续滚动
实现思路:
- 在新建 HTML 页面中,添加 <h3> 和无序列表,用无序列表显示 6 本畅销书籍的名称
- 添加 CSS 规则,重点设置无序列表的父版块 div(id="book") 的宽度和高度,使其只能显示前 3 个列表项,溢出的后 3 项使用 overflow: hidden 属性隐藏
- 在 HTML 文件中导入 jQuery 框架,并添加 <script></script> 标签对
- 声明 moveBook() 函数,在函数体中,声明变量 stopScroll 表示是否停止滚动,初始值是 false,表示不停止滚动
实现代码:
核心代码:
<script type="text/javascript">function moveBook(){var stopScroll=false;var marginTop=0;setInterval(function(){if(stopScroll) return;$(".express").children("li").first().animate({marginTop:marginTop--},0,function(){if (!$(this).is(":animated")) {if ((-marginTop)>$(this).height()) {$(this).css("margin-top",0).appendTo($(".express"));marginTop=0;}}});},50);$(".express").mouseover(function(){stopScroll=true;}).mouseout(function(){stopScroll=false;});}$(function(){moveBook();});
</script>
完整代码:
<!DOCTYPE html>
<html><head><meta charset="utf-8" /><title>无标题文档</title></head><style type="text/css">*{margin: 0px;padding: 0px;}body{font-size: 12px;}ul{list-style: none}ul li{height: 25px; line-height: 25px;}h3{width: 162px; height: 30px; line-height: 30px;text-align: center;background-color: #C33;}</style><script type="text/javascript" src="js/jquery-3.3.1.min.js"></script><script type="text/javascript">function moveBook(){var stopScroll=false;var marginTop=0;setInterval(function(){if(stopScroll) return;$(".express").children("li").first().animate({marginTop:marginTop--},0,function(){if (!$(this).is(":animated")) {if ((-marginTop)>$(this).height()) {$(this).css("margin-top",0).appendTo($(".express"));marginTop=0;}}});},50);$(".express").mouseover(function(){stopScroll=true;}).mouseout(function(){stopScroll=false;});}$(function(){moveBook();});</script><body><h3>进七日畅销榜</h3><div id="book"><ul class="express"><li>傲慢与偏见</li><li>玻璃鞋全集(50集34VCD)</li><li>澳大利亚:假日之旅</li><li>浪漫地中海:假日之旅</li><li>欧洲风情:假日之旅</li><li>社交疯狂英语</li></ul></div></body>
</html>