JS實現列表上下滾動模擬廣播消息

實現效果

  1. 無限循環
  2. 懸停停止
  3. 增加了消息出現的暫停
    在這裏插入圖片描述

實現代碼

代碼使用的是到處CV的那個書訊快遞的版本,原始代碼還是不錯得,我自己在此基礎上做了改進,實現滾動暫停的效果。

記得導入Jquery

<!DOCTYPE html>
<html>
	<head>
		<style>
			.scrollNotice {
				height: 30px;
				width: 100px;
				overflow: hidden;
			}

			.scrollNotice li {
				height: 30px;
				text-overflow: ellipsis;
				white-space:nowrap;
				overflow: hidden;
			}
		</style>
	</head>
	<body>
		<ul id="scrollNotice" class="scrollNotice">
			<li id="noticeId1">1・IDEA*****************************</li>
			<li id="noticeId2">2・Java*****************************</li>
			<li id="noticeId3">3・Js</li>
			<li id="noticeId4">4・Vue*****************************</li>
			<li id="noticeId5">5・Hadoop</li>
			<li id="noticeId6">6・Spark</li>
		</ul>
		<script src="static/jquery/jquery-1.8.3.js"></script>
		<script>
			$(document).ready(function() {

				$('.scrollNotice li').click(function() {
					console.log($(this).attr('id'))
				})

				function noticeMove() {
					var marginTop = 0; //上邊距的偏移量
					var stop = false;
					setInterval(function() {
						if (stop == true) {
							return;
						}
						$("#scrollNotice").children("li").first().animate({
							"margin-top": marginTop--
						}, 0, function() {
							var $li = $(this);
							if (!$li.is(":animated")) { //第一個li的動畫結束時
								if (-marginTop > $li.height()) {
									$li.css("margin-top", "0px").appendTo($("#scrollNotice"));
									marginTop = 0;
									// new begin
									stop = true
									// 停止3s,如果懸停則不做任何事
									// var $that = $(this)
									setTimeout(function() {
										// 這裏判斷懸停不能取this,因爲this已經不在當前界面上了
										// 使用父類的子類是否有懸停即可
										if($("#scrollNotice").find("li:hover").length == 0) {
											stop = false
										}
									}, 2000)
									// new end
								}
							}
						});
					}, 30); // 調整這個數字可以控制滾動的速度
					//鼠標懸停於li上時
					$("#scrollNotice").hover(function() {
						$(this).css("cursor", "pointer");
						stop = true; //停止動畫
					}, function() {
						stop = false; //開始動畫
					});
				}
				noticeMove();
			});
		</script>
	</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章