我试图在div中突出显示某些文字,其中突出显示是所述文字中的固定行。到目前为止,我有一个非常简单的解决方案,使用两个div,一个包含文本,另一个用作高亮,当你滚动文本时,它将通过高亮div。
HTML如下:
<div id="test">
text...
</div>
<div id="highlight"></div>
CSS是:
#highlight {
position: fixed;
top: 50%;
width: 100%;
background-color: #ccff00;
height: 30px;
opacity: 0.6;
}
#test{
position: absolute;
font-size: 30px;
top: 50%;
}
A demo of it can be found here
我想知道是否有人知道如何制作它以便滚动文本的方式可以在用户滚动时完成,下一行会突出显示。目前它正常滚动,因此突出显示可能会错过一条线,或者不突出显示整行。另外,我想知道如何使文本一直滚动到底部是最好的。是否会在顶部工作中添加与偏移量相同的边距?任何这些的替代解决方案也将受到赞赏。
答案 0 :(得分:2)
尝试在滚动时向窗口添加事件侦听器。然后通过取scrollY % line-height
计算偏移量,并将突出显示上边距设置为该值的负值。
下面的JavaScript:
var highlight = document.querySelector("#highlight");
window.addEventListener('scroll', function(e){
var y = window.scrollY;
var offset = y % 30;
highlight.style.marginTop = - y % 30 + "px";
});
答案 1 :(得分:1)
不确定是否这样 https://jsfiddle.net/ok0x3apo/6/是您正在寻找的
您可以看到我正在重新输入输入的文字,以便在页面滚动时逐行突出显示。
var el = document.getElementById("text"),
content = el.innerHTML.replace(/ |^\s+|\s+$/g,""),
lines = content.split(/\./);
var html = "";
for(var i in lines){
html+="<p class='clear_display' id='id_"+i+"'>"+lines[i]+".</p>";
};
document.getElementById("text").innerHTML=html;
您可以更改&#34; clear_display&#34;关于如何使用文本块的课程。
function calledEveryScroll() {
var scrollPosition = $(window).scrollTop();
for(var i in lines){
var currentSection = document.querySelector("#id_"+i+"");
var sectionTop = currentSection.offsetTop;
if (scrollPosition<=0){
$(".clear_display").removeClass('active');
document.querySelector("#id_0").className += " active";
}
if (scrollPosition >= sectionTop-50) {
$(".clear_display").removeClass('active');
if (!$(currentSection).hasClass('active')) {
$(currentSection).addClass('active');
if(previous){
if(currentSection.offsetTop==previous.offsetTop){
$(previous).addClass('active');
}
}
var previous = currentSection;
}
//return false;
}
}
}
function resizing(){
var offset =100;
var bottom = $(window).height()-offset;
$('#text').css('margin-bottom',bottom);
}
此功能会在页面滚动时检查每一行。如果滚动到达底部,我计算边距 - 底部。希望它有帮助。