简体   繁体   中英

jQuery: HTML5 audio control floating only when playing

I am using the following script to with the audio controls class="box follow-scroll" to make it float while the page is scrolling. But I was wondering if it possible to make it float only while the audio is in either play or pause mode? If it stopped it didn't start, it stays where it is.

$(window).load(function(){

    (function($) {
        var element = $('.follow-scroll'),
            originalY = element.offset().top;

        var topMargin = 20;
        element.css('position', 'relative');

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

            element.stop(false, false).animate({
                top: scrollTop < originalY ? 0 : scrollTop - originalY + topMargin
            }, 300);
        });
    })(jQuery);

});

The html:

<audio controls class="box follow-scroll">
<source src="http://techslides.com/demos/samples/sample.ogg" type="audio/ogg">
<source src="http://techslides.com/demos/samples/sample.mp3" type="audio/mpeg">
</audio>

Add two eventlisteners to your audio element. One that starts floating when your audio is playing, and one that resets your audio element when it is paused. In the following example the stopFloating() resets your audio element by setting var scrollTop = 0; to zero. You can of course further tune this function.

Something like:

var element = $('.follow-scroll'), originalY = element.offset().top;

var topMargin = 20;
element.css('position', 'relative');

element[0].addEventListener("playing", function() {
    startFloating();
});

element[0].addEventListener("pause", function() {
    stopFloating();
});


function startFloating () {
    $(window).on('scroll', function(event) {

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

        element.stop(false, false).animate({
                top: scrollTop < originalY ? 0 : scrollTop - originalY + topMargin
        }, 300);    
    });
}

// Reset your element
function stopFloating () {
    $(window).on('scroll', function(event) {

        var scrollTop = 0;

        element.stop(false, false).animate({
                top: scrollTop < originalY ? 0 : scrollTop - originalY + topMargin
        }, 300);    
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM