用户滚过元素

时间:2015-10-15 21:23:02

标签: javascript jquery

问题:

一旦用户滚过标题,我就会尝试淡入淡出{foutOut div class="audioBox"。我有什么似乎工作正常,除了页面加载和我已经超过标题的835px高度/

问:我看到的是当我滚动audioBox快速淡入然后淡出时,尽管scroll >= header如何防止这种情况发生? < / p>

scripts.js中

// If the reader scrolls past header, show audioBox
var scroll = $(window).scrollTop();
var header = $("header").height();

if (scroll >= header) {
    $(".audioBox").fadeIn();
} else if (scroll <= header) {
    $(".audioBox").fadeOut();
}

2 个答案:

答案 0 :(得分:2)

我尝试在http://jsfiddle.net/3wqfp2ch/1/的jsfiddle中实现你所描述的内容。

基于以下想法,我的处理方式略有不同:

  • 我个人更喜欢让CSS通过类来处理视觉内容,让jQuery承担控制何时添加/删除类的简单责任。我认为它可以使两个系统之间建立更好的关系,并让每个系统更好地完成他们的工作。更整洁。
  • 我没有看到你在窗口上监听滚动事件的位置,这对于确定用户的滚动位置是否在标题之前或之后是必不可少的,因此将其包含在我的代码中
  • 我不认为我们需要多个if条件 - 只有一个问题:“滚动位置是否大于标题高度?”。

这是JS:

var headerHeight = $("header").height();
var audioBox = $('#audioBox');

$(window).on('scroll', function(){
  var scrollPosition = $(window).scrollTop();

  if (scrollPosition > headerHeight) {
    audioBox.addClass('is-visible');
  } else {
    audioBox.removeClass('is-visible');
  }
});

http://jsfiddle.net/3wqfp2ch/1/查看我的小提琴,了解HTML&amp;与此相关的CSS,以及将它们放在一起的工作演示。

我无法测试这是否会遇到与您在jsfiddle已经超过标题高度的点加载相同的问题,但我不会期望您使用上述代码描述的行为。

让我知道你是怎么过的!

答案 1 :(得分:0)

始终致电.fadeIn().fadeOut() 并且条件重叠可能是问题。

试试这个:

// If the reader scrolls past header, show audioBox
var scroll = $(window).scrollTop();
var header = $("header").offset().top + $("header").height(); // should include the header's offset as well

if (scroll >= header) {
    $(".audioBox:hidden").fadeIn();
} else if (scroll < header) {
    $(".audioBox:visible").fadeOut();
}
相关问题