【问题标题】:Start functions when bootstrap carousel-selector has class selected当引导轮播选择器选择了类时启动函数
【发布时间】:2018-10-04 21:48:34
【问题描述】:

以下函数显示计数。它在引导轮播中。

我想在引导轮播选择器有class="selected" 而不是在页面加载时立即启动此功能。

第二个条件应该是用户确实在页面的那个部分(#video)。因此,当他没有看到与功能相关的部分时(可能通过某种方式通过 scrollspy?),该功能不会启动。我该怎么做?

$('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

关于此页面的问题(最后一张幻灯片):https://bm-translations.de/km#video

【问题讨论】:

  • 你能解释更多before AND if the user really is on that part of page吗?
  • 我编辑了问题
  • 你能给我们一个你在jsfiddle(或任何其他平台)中的html代码的例子吗?谢谢

标签: jquery twitter-bootstrap carousel


【解决方案1】:

第一个条件:
检查 Carousell 是否有 Class

if $('#yourcaroussellID').hasClass('selected')

第二个条件
比较用户在页面上的位置和元素在页面上的位置

isInViewport = function() {
    var videoTop = $('#carouselMarketing1').offset().top;
    var videoBottom = videoTop + $('#carouselMarketing1').outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return videoBottom > viewportTop && videoTop < viewportBottom;
}

您需要定期检查组合 ifs 以查看滚动的变化:

myInterval = setInterval(function(){ 
    if ($('#carousel-selector-4').hasClass('selected') && (isInViewport())) { 
        yourCounter();
        myStopFunction();
    }
}, 1000);

让你的计数器成为你可以调用的函数:

yourCounter = function() {
    $('.count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 4000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.ceil(now));
            }
        });
    });
}

为区间做一个停止函数:

function myStopFunction() {
    clearInterval(myInterval );
}

【讨论】:

  • 我试过了,但没用: var usertop = $('html').offset().top; var videotop = $('#carouselMarketing1').offset().top; $('#carouselMarketing1').on('slide.bs.carousel', function() { if ($('#carousel-selector-4').hasClass('selected') && (usertop >= videotop)) { $('.count').each(function () { $(this).prop('Counter',0).animate({ Counter: $(this).text() }, { duration: 4000, 缓动: 'swing', step: function (now) { $(this).text(Math.ceil(now)); } }); }); } });
  • 检查这个小提琴,它可能会帮助你:jsfiddle.net/7fheh60x,我还稍微调整了代码,为你提供更多现成的解决方案,而不仅仅是步骤本身。
  • 现在它一次又一次地向前和向后计数。我猜它的间隔的原因?
  • 你应该把你的计数器移动到一个函数,并在你确定用户正在看视频后调用这个函数,然后清除间隔:像这样:w3schools.com/jsref/met_win_clearinterval.asp。如果您将计数器放在间隔中,它将在每个间隔步骤中重新开始。
  • @KrystianManthey 我在我的帖子和这个小提琴中添加了一个明确间隔的示例:jsfiddle.net/7fheh60x/1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多