---
title: "jQuery实现文字上下【渐进】滚动"
author: "青春..荒唐"
date: "2018-09-21T09:29:02Z"
tags: ["jQuery"]
categories: ["Web前端"]
slug: "jquery"
draft: false
lastmod: "2018-09-21T09:59:58Z"
id: 2431079
url: "https://570109268.iteye.com/blog/2431079"
---

【前言】

    jQuery实现文字上下滚动，原理很简单（jQuery动画+css方法）。这里简单总结下，以后讲课备录。

 

【主体】

1、知识点

     （1）animate方法实现向上滚动

     （2）css方法重定义样式

 

2、原理

     通过jquery动画向上滚动，之后通过css方法重定义位置，接下来通过appendTo()方法将上一条记录插入到最后，以此实现依次循环播放。（注意：append()方法与appendTo()区别[jQuery中append()和appendTo()的区别](/blog/2431080)

）

 

3、代码

下面直接上代码，

```
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>文字滚动</title>
	<style type="text/css">
		*{
			margin:0px;
			padding: 0px;
		}
		li{
			list-style-type: none;
		}
		.main{
			width: 600px;
			height: 50px;
			border: 1px solid #888;
			margin: 10px auto;
			overflow: hidden;
		}
		.main ul li{
			line-height: 50px;
			background-color: rgba(0,0,0,0.3);
		}
		.main ul li:hover{
			background-color: rgba(0,0,0,0.2);
		}
	</style>
	<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
	<script type="text/javascript">
		$(function(){
			var timeId = setInterval(play,1500);
			function play(){
				$(".main ul").animate({
					"marginTop": "-50px"},
					600, function() {
					/* stuff to do after animation is complete */
					$(this).css({"marginTop":0}).children("li:first").appendTo(this);
				});
			}
			$(".main").hover(function() {
				/* Stuff to do when the mouse enters the element */
				clearInterval(timeId);
			}, function() {
				/* Stuff to do when the mouse leaves the element */
				timeId = setInterval(play,1500);
			});
		})
	</script>
</head>
<body>
<div class="main">
	<ul>
		<li>我是1</li>
		<li>我是2</li>
		<li>我是3</li>
		<li>我是4</li>
		<li>我是5</li>
		<li>我是6</li>
	</ul>
</div>
</body>
</html>
```

 

4、拓展

    选择ul下的第一个li有多种方法，除了通过$("ul li:first")之外，也可以通过索引获取。例如$("ul li").eq(0)

 

先写到这里，以后有时间继续完善

.