【问题标题】:Active when scrolled to its section滚动到其部分时激活
【发布时间】:2021-08-23 14:52:17
【问题描述】:

我试图在用户滚动到其部分时激活此百分比进度条,目前它会在您刷新页面或单击 url 时立即移动。

<svg viewBox="0 0 36 36" class="circular-chart orange">
  <path class="circle-bg"
    d="M18 2.0845
      a 15.9155 15.9155 0 0 1 0 31.831
      a 15.9155 15.9155 0 0 1 0 -31.831"
  />
  <path class="circle"
    stroke-dasharray="29, 100"
    d="M18 2.0845
      a 15.9155 15.9155 0 0 1 0 31.831
      a 15.9155 15.9155 0 0 1 0 -31.831"
  />
  <text x="18" y="20.35" class="percentage">29%</text>
</svg>

.circular-chart {
 display: block;
 margin: 10px auto;
 max-width: 80%;
 max-height: 250px;
}

.circle-bg {
 fill: none;
 stroke: #eee;
 stroke-width: 3.8;
}

.circle {
 fill: none;
 stroke-width: 2.8;
 stroke-linecap: round;
 animation: progress 1s ease-out forwards;
}

@keyframes progress {
0% {
 stroke-dasharray: 0 100;
   }
 }

.circular-chart.orange .circle {
 stroke: #ea5031;
 }

.percentage {
 fill: #666;
 font-family: sans-serif;
 font-size: 0.5em;
 text-anchor: middle;
 } 

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    您应该检查文档的事件滚动(请限制它)元素顶部位置是否在文档滚动的可见范围内。如果可见,则向将启动动画的元素添加一个类。

    css:

    .circle {
        fill: none;
        stroke-width: 2.8;
        stroke-linecap: round;
    }
    
    .animated {
        animation: progress 1s ease-out forwards;
    }
    

    js:

    var lastKnownScrollPosition;
    
    
    function isScrolledIntoView(el, is_partially, tolerance) {
        if (el.length) {
            el = el[0]
        }
        var rect = el.getBoundingClientRect();
        var elemTop = rect.top;
        var elemBottom = rect.bottom;
        var isVisible
        if (is_partially) {
            isVisible = (elemTop < window.innerHeight - tolerance) && (elemBottom >= 0 + tolerance);
        } else {
            isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
        }
        return isVisible;
    }
    
    function do_install_scroll_listener() {
        var ticking = false;
        lastKnownScrollPosition = window.scrollY;
    
        function foo_scroll() {
            lastKnownScrollPosition = window.scrollY;
            if (!ticking) {
                window.requestAnimationFrame(function () {
                    do_select_closest_video_to_play(YOUR_ELEMENT);
                    ticking = false;
                });
                ticking = true;
            }
        }
        $(document).on('scroll', foo_scroll)
    }
    
    function do_select_closest_video_to_play(my_video_container) {
        if (isScrolledIntoView(my_video_container, true, 40)) {
            $(my_video_container).addClass("animated");
        }
    }
    
    do_install_scroll_listener();
    

    一个工作示例

    https://jsfiddle.net/itgoldman/kr13sjod/4/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 2020-08-07
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多