用户滚动经过div后切换图标

时间:2015-10-23 18:20:30

标签: javascript jquery

目标

当音频片段暂停并且用户滚动浏览故事中的块引用时,我希望将FontAwesome图标从volume-off切换回默认的volume-up。然后,将音频剪辑重置为开头。

问题

但是,切换几乎立即发生,而不是在块视图不在视野时。 我的if语句似乎已关闭。想知道我是否必须在其偏移量之外加入元素的innerHeight以确保不会发生这种情况。曾经是console.log()的一大堆成功。

scripts.js中

// Position of the blockquotes
var scroll = $(window).scrollTop();

var bathtubOffset = $(".bathtub").offset();
var behindOffset = $(".behind").offset();
var curiousOffset = $(".curious").offset();
var haystackOffset = $(".haystack").offset();
var wishesOffset = $(".wishes").offset();

$(window).scroll(function(){
    if (scroll >= bathtubOffset && bathtub.paused == true) {
        $(".bathtub").removeClass("fa-volume-off");
        $(".bathtub").addClass("fa-volume-up");
        bathtub.currentTime = 0 // Reset audio clip to the beginning
    }
});

的index.html

            <blockquote class="blockquote--simple">
                <audio id="wishes">
                   <source src="assets/audio/mp3/wishes.mp3">
                   <source src="assets/audio/ogg/wishes.ogg">
                </audio>

                <p class="blockquote__text--simple">"Put your wishes down because that was the hardest thing that we dealt with was not knowing what he wanted." </p>

                <div class="blockquote__icons">
                    <p>— Brian Fowell</p>
                    <a href="https://twitter.com/home?status=%22Put%20your%20wishes%20down%20because%20that%20was%20the%20hardest%20thing%20that%20we%20dealt%20with%22%20http%3A//bdnsun.ca/bdnhoarders%0A" target="_blank"><i class="blockquote__icon--simple fa fa-twitter"></i></a>
                    <i class="blockquote__icon--simple fa fa-volume-up wishes inline"></i>
                </div>
            </blockquote>

1 个答案:

答案 0 :(得分:3)

您永远不会刷新scroll并且您没有使用top的{​​{1}}属性。

bathtubOffset在全局范围内调用,永远不会在侦听器中设置。

var scroll = $(window).scrollTop();

编辑:正如@GreggDuncan指出的那样,$(window).scroll(function(){ //Update scroll scroll = $(window).scrollTop(); //Also change to using bathtubOffset.top if (scroll >= bathtubOffset.top && bathtub.paused == true) { $(".bathtub").removeClass("fa-volume-off"); $(".bathtub").addClass("fa-volume-up"); bathtub.currentTime = 0 // Reset audio clip to the beginning } }); 。top`

jQuery的offset method返回一个包含DOM元素的所有偏移值的对象。这包括bathtubOffset is the object with all the offset values. It needstopleft等。您的滚动方法仅查看垂直滚动,您只需要height值。因此,您可以访问top的属性:offset