开发者

Get position relative to browser window

I have 2 divs and one is nested in the other. I want to get the child div position relative to browser window. The use case is this: when user scroll down browser, I want to detect the position of the child div and if it is 100px above the bottom of the brow开发者_Go百科ser window, I want to fade it out slowly.

How do I do that with jQuery? The 2 divs have relative position or absolution position but not fixed position.


Try this:

$(window).scroll(function () {
 var distanceFromBottom = 100;
 if ( ( $("#outerdiv").offset().top + $("#innerdiv").height() - $(window).scrollTop() ) > $(window).height() - distanceFromBottom ) {
  $("#innerdiv").fadeOut("slow");
 } else {
  $("#innerdiv").fadeIn("slow");
 }
})

You didn't state if you wanted the #innerdiv to fade back in if greater than 100 pixels from the bottom, but I wrote this assuming that you did... In this case, you would need to detect the offset of the #outerdiv if you want the #innerdiv to fade back in as an invisible element has no position.

If you don't want the #innerdiv to fade back in then change the if statement to look at the #innerdiv element and remove the else portion of the function.


Edit: Looking at your example page, I'm guessing you wanted this effect to work on the music player. Since, it's probably not the best idea to fade or slowly hide an embedded object using jQuery - it just doesn't animate well - so, I just did it abruptly. The above script will still work, but as you can see in the revision below, you don't have to use 2 Divs, I used the div and the embedded object within it. The outer div should closely wrap the inner div for this script to work, so you can't use the div with id "container-msg" in this case.

$(window).scroll(function () {
 var distanceFromBottom = 100;
 if ( ( $(".windowMediaPlayer").offset().top + $(".windowMediaPlayer object").height() - $(window).scrollTop() ) > $(window).height() - distanceFromBottom ) {
  $(".windowMediaPlayer object").hide();
 } else {
  $(".windowMediaPlayer object").show();
 }
})

I modified your example and saved it to this pastebin so you can see it working.

Edit: Oops, you said you wanted it to disappear when it got closer to the bottom... I just changed the "<" to ">" and now it should do what you want. I updated the pastebin code too.


var inner_offset = $("#innerdiv").offset();
var window_size = $(window).height();

if( ( inner_offset.top + $("#innerdiv").height() ) > window_size - 100 )
    $("#innerdiv").fadeOut("slow");

Not vetted, but should give you the general idea.


offset at the jQuery documentation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜