在视口中运行JS函数。

时间:2014-06-14 19:57:36

标签: javascript jquery scroll viewport

我在这里找到了如何做一个计数器,我将在滚动网站上使用它。

我使用以下代码:

$(function() {
    function count($this){
        var current = parseInt($this.html(), 10);
        $this.html(++current);
        if(current !== $this.data('count')){
        setTimeout(function(){count($this)}, 10);
    }   
}
  $("span").each(function() {
  $(this).data('count', parseInt($(this).html(), 10));
  $(this).html('0');
  count($(this));
  });
});

我已尝试包含以下代码,但我不确定我是否正确添加了该代码:

      if ($('element').visible(true)) {

}

这是一个指向当前没有if语句的Jfiddle的链接。任何帮助将不胜感激。

http://jsfiddle.net/WpJxn/257/

1 个答案:

答案 0 :(得分:1)

这是你应该看到的:Check if element is visible after scrolling

以下是演示此技术的示例:http://jsfiddle.net/XYS2G/ - 只需尝试滚动“结果”窗口。

HTML:

<div class="indicators">
    <span class="indicator" data-id="section1">section1</span>
    <span class="indicator" data-id="section2">section2</span>
    <span class="indicator" data-id="section3">section3</span>
    <span class="indicator" data-id="section4">section4</span>
    <span class="indicator" data-id="section5">section5</span>
    <span class="indicator" data-id="section6">section6</span>
</div>
<div class="sections">
    <div class="section" id="section1">section1</div>
    <div class="section" id="section2">section2</div>
    <div class="section" id="section3">section3</div>
    <div class="section" id="section4">section4</div>
    <div class="section" id="section5">section5</div>
    <div class="section" id="section6">section6</div>
</div>

CSS:

.indicators { position: fixed; }
.section { height: 150px; }

JavaScript的:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

function refreshIndicators() {
    $('.indicator').each(function () {
        if (isScrolledIntoView($('#' + $(this).attr('data-id')))) {
            $(this).css('color', 'red');
        } else {
            $(this).css('color', 'black');
        }
    });
}

refreshIndicators();

$(window).bind('scroll', refreshIndicators);