问题描述
我正在尝试使用javascript和CSS创建自动滚动字幕,但我也希望能够使用鼠标滚轮手动滚动字幕。选框功能符合预期,即它会自动滚动并循环良好,但我不知道如何合并手动滚动。这是我正在使用的代码。有什么想法吗?
<doctype HTML>
<body onload="init()">
<main>
<div id="marquee_replacement" class="scrollbar" onmouSEOut="startit();" onmouSEOver="stop();">
<p>some text some text some text some text some text some text some text some text</p>
<p>some text some text some text some text some text some text some text some text</p>
<p>some text some text some text some text some text some text some text some text</p>
<p>images are also present</p>
<p class="spacer"></p>
</div>
<script type="text/javascript">
//
var speed = 2; // change scroll speed with this value
/**
* Initialize the marquee,and start the marquee by calling the marquee function.
*/
function init() {
var el = document.getElementById("marquee_replacement");
el.style.overflow = 'hidden'; //issue is fixed by setting this to auto
scrollFromBottom();
}
var go = 0;
var timeout = '';
/**
* This is where the scroll action happens.
* Recursive method until stopped.
*/
function scrollFromBottom() {
clearTimeout(timeout);
var el = document.getElementById("marquee_replacement");
if (el.scrollTop >= el.scrollHeight - 150) {
el.scrollTop = 0;
};
el.scrollTop = el.scrollTop + speed;
if (go == 0) {
timeout = setTimeout(scrollFromBottom,50);
};
}
/**
* Set the stop variable to be true (will stop the marquee at the next pass).
*/
function stop() {
go = 1;
}
/**
* Set the stop variable to be false and call the marquee function.
*/
function startit() {
go = 0;
scrollFromBottom();
}
</script>
<!--CSS for Marquee-->
<style type="text/css">
#marquee_replacement.scrollbar {
width: auto;
height: 150px;
overflow-y: scroll; /*issue is fixed by setting this to auto*/
}
.scrollbar::-webkit-scrollbar {
display: none;
}
#marquee_replacement {
-ms-overflow-style: none;
/* IE and Edge */
scrollbar-width: none;
/* Firefox */
}
#marquee_replacement p.spacer {
height: 150px;
}
</style>
</main>
</body>
编辑: 很抱歉没有提供最小的可复制示例的新手错误。我将更新上面的代码以提供MREX,以便将来的读者更容易理解该问题。另外,我解决了这个问题。如果我将CSS和javascript部分的溢出值分别设置为auto而不是分别进行滚动和隐藏,则它将用作自动滚动字幕和手动滚动文本框。
解决方法
setTimeout
使用函数,而不是带代码的字符串。这样做:setTimeout(scrollFromBottom,50)
我知道了。如果将来有人需要,我必须将el.style.overflow = 'auto';
设置为auto而不是隐藏,并将CSS溢出设置为overflow-y: auto;
设置为auto而不是滚动。现在,它会自动和手动滚动!