gpt4 book ai didi

javascript垂直滚动文本到下一行

转载 作者:行者123 更新时间:2023-11-28 15:26:05 24 4
gpt4 key购买 nike

我将单词包裹在 span 中,并在歌曲播放时将文本单词突出显示为歌词(以秒为单位计时)。

我的问题是有没有一种方法可以检测突出显示的文本何时会从容器底部(父溢出包装器)运行,所以我将文本移动到下一行,或者可能移动几行以显示下一个传入的突出显示行.如有必要,我可以为所有跨度提供不同的 ID。我可以在内包装 div 上使用 scrollTop,但我如何计算突出显示的单词的位置?

例如,当带有红色类的单词熄灭时:

#wrap{
width:300px;
height:100px;
background:#ccc;
overflow-y:auto;
}

.red{
color:red;
}
<div id="wrap">
<div id="inner-wrap">
<span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span class="red">Lorem</span> <span class="red">ipsum</span> <span class="red">dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span> <span>Lorem</span> <span>ipsum</span> <span>dolor</span> <span>sit</span> <span>amet.</span>
</div>
</div>

最佳答案

这是一个例子。 <span>的位置包装器内使用其 offsetTop 确定.然后使用其 scrollTop 将包装器滚动到该位置。属性(property)。

// Example data, <span>ified
var wrap = document.querySelector("#wrap");
wrap.innerHTML = "Lorem ipsum dolor sit amet. "
.repeat(30).split(" ")
.map(w => `<span>${w}</span>`).join(" ");
var spans = document.querySelectorAll("#wrap span");
var selected = null;

// Scroll to span function, also highlights the span
function scrollTo(span) {
// Highlighting
if (selected) {
selected.className = "";
}
span.className = "red";
selected = span;

// Actual scrolling (span is centered in the wrapper)
wrap.scrollTop = span.offsetTop - 35;
}

// Button listener
document.querySelector("#button").onclick = function() {
scrollTo(spans[Math.floor(Math.random() * spans.length)]);
};
#wrap {
height: 70px;
overflow-y: scroll;
}

.red {
color: red;
}
<div id="wrap"></div>
<button id="button">Select random span</button>

关于javascript垂直滚动文本到下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45218566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com