当元素出现在浏览器中时隐藏div

我有一个高度超过1000像素的网页。 有一个重要的文字,我需要一直显示给访客。 我在页面顶部放置了一个具有固定属性的20像素高DIV,但该DIV的内容出现在中间可用的浏览器中。 我想要隐藏顶部div,但是当我从中间div向上滚动时,我想显示顶部div。

你在找这样的东西吗?

鉴于此HTML:

a bunch of text, and duplicate this several times. I used lorem ipsum

Here is the interesting text.

a bunch more text, and duplicate this several times. I used lorem ipsum

span#interesting可见时,您可以使用此JavaScript显示div,并在不可见时隐藏它:

 // Add a div to contain a copy of the interesting text var interestingOffscreen = $('
') .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);

并非所有这些都是绝对必要的,但它看起来很酷。