2

I have a button back-to-top that is affixed to the left side of the screen - it uses scrollTop to slide-scroll to the top of the page when it's clicked. When the page the loads, the button is visible and does not cover anything that is readable etc.

When a user scrolls down the page, the button goes over certain DIVs that have text content. When the button goes into such a DIV I want it to hide using .hide(). Can't get it to work, here's what I have:

    var p = $('a.back-to-top');
    var position = p.position();

    if(position == $('#about-me')){
        $('a.back-to-top').hide();
    }

Is if(position == $('#about-me')) the correct way to check if the button's position is in the #about-me DIV? Or, should I create a variable similar to position for the DIV?

EDIT: A messy but simple fiddle

4

2 回答 2

3

http://api.jquery.com/position/ - position() 方法返回一个具有 .left 和 .top 属性的位置对象。所以基本上,你不能将位置与选择器返回的某个对象进行比较。相反,您应该比较两个元素的“顶部”属性值。例如,您有:

var p = $('a.back-to-top');
var position = p.position();

也得到这个:

var aboutMePosition = $('#about-me').position();

然后你可以比较:

aboutMePosition.top 和 position.top 无论您需要哪种方式。

于 2012-12-01T16:17:54.480 回答
3

您将需要在回调中进行此检查 .. 可能$(window).scroll以便在每次窗口滚动时检查它;否则,仅在页面加载时检查。

我不认为你想使用position任何一个,因为这是相对于父母的位置。相反,您可能想要.offset. 这将返回一个包含topleft成员的对象。==比较没有意义,尤其是对于 jQuery 对象。你想使用:

$(window).on('scroll', function () {
   var offset = $("a.back-to-top").offset().top;

   var within = $("#about-me").offset().top;

   if (offset >= within && offset <= within + $("#about-me").height()) {
      $("a.back-to-top").hide();
   }
   else {
      $("a.back-to-top").show();
   }
});​

如果位置固定,则随着滚动的偏移量会.back-to-top发生变化,而静态块的偏移量不会改变,因此您可以进行此比较。

看看它在行动:http: //jsfiddle.net/QnhgF/

于 2012-12-01T16:19:32.170 回答