当元素出现在浏览器中时隐藏div [英] Hide div while an element appear in the browser
问题描述
我的网页高度超过1000像素。有一个重要的文字我需要一直显示给访客。我在页面顶部放置了一个具有固定属性的20像素高DIV,但该DIV的内容出现在中间可用的浏览器中。我想要隐藏顶部div,但是当我从中间div向上滚动时,我想显示顶部div。
I have a web page with a height more than 1000 pixels. There is an important text which I need to display all the time to a visitor. I placed a 20 pixel high DIV with a fixed property at the top of the page but the content of that DIV appears in the browser available in the middle. I want to hide the top div, but as I scrolled up from the middle div I want to show the top div.
推荐答案
你在寻找这样的东西吗?
Are you looking for something like this?
- http://jsfiddle.net/3vEaF/
鉴于此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 #interest时显示div
是可见的,当它不可见时隐藏它:
You can use this JavaScript to display a div when span#interesting
is visible, and hide it when it isn't visible:
// 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);
并非所有这些都是绝对必要的,但它看起来很酷。
Not all of this is strictly necessary, but it looks cool.
这篇关于当元素出现在浏览器中时隐藏div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!