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

时间:2011-12-11 10:08:47

标签: jquery

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

1 个答案:

答案 0 :(得分: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在span#interesting可见时显示div,并在不可见时隐藏它:

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

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