Js實現文字水平滾動


公司項目中有一個公告欄,寫的時候我先想到了用marquee,於是發現了marquee有很多弊端,當文字全部顯示完才出現新的文字,這樣不是很友好,然后一查發現marquee這個標簽已經被W3C標准廢棄了,也就是不再支持使用這個標簽了,於是我便用js+css去替代這個寫法,並且做到類似無縫滾動的效果。直接上代碼:

html代碼:

<div id="scroll_div" class="fl">
	<div id="scroll_begin">
		<span class="pad_right">這是第一條信息的內容這是第一條信息的內容這是第一條信息的內容</span>
		<span class="pad_right">這是第二條信息的內容這是第二條信息的內容這是第二條信息的內容</span>
		<span class="pad_right">這是第三條信息的內容這是第三條信息的內容這是第三條信息的內容</span>
		<span class="pad_right">這是第四條信息的內容這是第四條信息的內容這是第四條信息的內容</span>
		<span class="pad_right">這是第五條信息的內容這是第五條信息的內容這是第五條信息的內容</span>
	</div>
	<div id="scroll_end"></div>
</div>

css代碼:

#scroll_div {
	height: 30px;
	line-height: 30px;
	overflow: hidden;
	white-space: nowrap;
	width: 800px;
	background-color: #23527c;
	color: #d8d8d8;
	margin: 1rem 0;
	text-align: center;
}
#scroll_begin,#scroll_end {
	display: inline;
}
.pad_right {
	margin-left: 100px;
}

js代碼:

//文字橫向滾動
function ScrollImgLeft(){
	var speed = 40;//初始化速度 也就是字體的整體滾動速度
    var MyMar = null;//初始化一個變量為空 用來存放獲取到的文本內容
    var scroll_begin = document.getElementById("scroll_begin");//獲取滾動的開頭id
    var scroll_end = document.getElementById("scroll_end");//獲取滾動的結束id
    var scroll_div = document.getElementById("scroll_div");//獲取整體的開頭id
    scroll_end.innerHTML=scroll_begin.innerHTML;//滾動的是html內部的內容,原生知識!
    //定義一個方法
	function Marquee(){
		if(scroll_end.offsetWidth-scroll_div.scrollLeft<=0)
			scroll_div.scrollLeft-=scroll_begin.offsetWidth;
		else
			scroll_div.scrollLeft++;
	}
    MyMar=setInterval(Marquee,speed);//給上面的方法設置時間 setInterval
	//鼠標滑入這條公告欄的時候,清除上面的方法,讓公告欄暫停
	scroll_div.onmouseover = function(){
		clearInterval(MyMar);
	}
	//鼠標滑出這條公告欄的時候,公告欄繼續移動
	scroll_div.onmouseout = function(){
		MyMar = setInterval(Marquee,speed);
	}
}
ScrollImgLeft();

效果截圖:

在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM