要使用jQuery實(shí)現(xiàn)文字的左右滾動,需要頁面先調(diào)用jQuery庫,可以使用animate
方法結(jié)合marquee
效果。marquee-container
是文字滾動的容器,marquee-text
是需要滾動的文本。start-scroll
按鈕觸發(fā)滾動,stop-scroll
按鈕停止?jié)L動。scroll
函數(shù)負(fù)責(zé)實(shí)際滾動動作,通過animate
方法和遞歸調(diào)用實(shí)現(xiàn)循環(huán)滾動。以下是一個(gè)簡單的例子:
<div id=“marquee-container”>
<p id=“marquee-text”>這里是需要滾動的文字內(nèi)容…</p>
</div>
<button id=“start-scroll”>開始滾動</button>
<button id=“stop-scroll”>停止?jié)L動</button>
#marquee-container {
white-space: nowrap;
overflow: hidden;
width: 250px; /* 根據(jù)需要設(shè)置容器寬度 */
}
#marquee-text {
position: absolute;
}
\((document).ready(function() {
var \)marqueeText = \(('#marquee-text');
var scrollWidth = \)marqueeText[0].scrollWidth;
var containerWidth = $(‘#marquee-container’).width();
function scroll() {
$marqueeText.animate({
left: -scrollWidth + containerWidth
}, 10000, 'linear', function() {
$marqueeText.css('left', containerWidth);
scroll();
});
}
$(‘#start-scroll’).on(‘click’, function() {
scroll();
});
$(‘#stop-scroll’).on(‘click’, function() {
$marqueeText.stop();
});
});