2011-12-11 39 views
-3

我有一個高度超過1000像素的網頁。有一個重要的文本,我需要顯示所有的時間訪問者。我在頁面頂部放置了一個固定屬性的20像素高的DIV,但該DIV的內容出現在中間的可用瀏覽器中。我想隱藏頂部div,但是當我從中間div滾動時,我想顯示頂部div。當元素出現在瀏覽器中時隱藏div

+2

Hey Sumit,你的問題很不清楚,你能不能改寫一下,並提供一些你已經嘗試過的樣本? –

+0

這可能有助於檢測項目是否在屏幕上 - http://stackoverflow.com/questions/487073/jquery-check-if-element-is-visible-after-scroling - 特別是,[這個答案]( http://stackoverflow.com/a/3535028/232593) –

+0

我想他想要一個標題出現1.當用戶低於「摺疊」 - 也就是說,摺疊是「關閉」的觀看頂部區域 - 或2.當視圖不滾動到頂部時。 Sumit是否正確? – Garvin

回答

0

你在找這樣的事嗎?

鑑於這種HTML:

<p>a bunch of text, and duplicate this several times. I used lorem ipsum</p> 
<p><span id="interesting">Here is the interesting text.</span></p> 
<p>a bunch more text, and duplicate this several times. I used lorem ipsum</p> 

您可以使用此JavaScript來顯示一個div時span#interesting是可見的,並且隱藏它時,它是不可見的:

// Add a div to contain a copy of the interesting text 
var interestingOffscreen = $('<div/>') 
    .attr('id', 'interesting') 
    .text($("span#interesting").text()); 

$('body').prepend(interestingOffscreen); 

// Center the display of that copy 
interestingOffscreen.css(
    'margin-left', 
    -(interestingOffscreen.outerWidth()/2) 
); 

// Detect when it is offscreen/onscreen and react  
function isScrolledIntoView(elem) 
{ 
    var docViewTop = $(window).scrollTop(); 
    var docViewBottom = docViewTop + $(window).height(); 

    var elemTop = $(elem).offset().top; 
    var elemBottom = elemTop + $(elem).height(); 

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)); 
} 

var isNotVisibleHandler; // forward declaration 

function isVisibleHandler() 
{ 
    if(isScrolledIntoView($("span#interesting"))) 
    { 
     $(window).unbind('scroll'); 
     interestingOffscreen.fadeOut(
      function() { 
       $(window).scroll(isNotVisibleHandler); 
       $(window).scroll(); // force detection 
      } 
     ); 
    } 
} 

isNotVisibleHandler = function() 
{ 
    if(!isScrolledIntoView($("span#interesting"))) 
    { 
     $(window).unbind('scroll'); 
     interestingOffscreen.fadeIn(
      function() { 
       $(window).scroll(isVisibleHandler); 
       $(window).scroll(); // force detection 
      } 
     ); 
    } 
}; 

$(window).scroll(isVisibleHandler); 

並非所有這些都是嚴格必要的,但我t看起來很酷。

相關問題