2016-11-15 25 views
1

我想突出顯示div中的某些文本,突出顯示是文本中的固定行。到目前爲止,我已經有了一個非常簡單的解決方案,它使用兩個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

我不知道是否有人知道如何讓這個滾動文本可以做作爲用戶滾動的方式,下一行將突出顯示。目前它正常滾動,所以突出顯示可能會錯過一行,或者不突出顯示完整行。另外,我想知道如何讓文本一直滾動到底部最好。是否會在頂部工作中添加與偏移量相同大小的邊距?任何此類替代解決方案也將受到讚賞。

回答

1

嘗試在滾動時向窗口添加事件偵聽器。然後通過取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"; 
}); 

See Working Fiddle

1

不知道這 https://jsfiddle.net/ok0x3apo/6/是你在找什麼

你可以看到,我remodifying輸入的文本,得到的線高亮線作爲頁面滾動。

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; 

您可以對「clear_display」類進行更改,以瞭解如何更改文本塊。

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); 
} 

此函數檢查頁面滾動時的每一行。爲了滾動到達底部,我正在計算margin-bottom.Hope它有幫助。