滚动时如何填充svg [英] How to fill svg when scrolling

查看:117
本文介绍了滚动时如何填充svg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有svg行:

<svg class="filling" width="500" height="10" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <path data-over-line="" d="M90,5 L500,5" stroke="#e2e2e2" fill="transparent" stroke-width="4" style="stroke-dashoffset: 0px;"></path>
</svg>

我需要在滚动页面时逐渐用不同的颜色填充它.怎么做?

I need when scroll the page it is gradually filled with a different color. How to do it?

推荐答案

我不确定您最终希望滚动条采用什么形状,但这是一个简单的解决方案.我们在您的灰线上方绘制一条蓝线,以指示滚动进度.行的长度是通过计算我们滚动页面的距离来确定的.

I am not sure what shape you ultimately want for your scrollbar, but here is a simple solution. We draw a blue line on top of your grey line to indicate scroll progress. The length of the line is determined by calculating how far done the page we have scrolled.

如果最终希望使滚动条的形状不是直线或矩形,则需要采取其他方法.

If you ultimately want to have the scrollbar be a shape other than a line or a rectangle, you will need to take a different approach.

SVG(稍作修改):

SVG (modified a little):

<svg class="filling" width="500" height="10" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <line x1="90" y1="5" x2="500" y2="5" stroke="#e2e2e2" fill="transparent" stroke-width="4" />
    <line x1="90" y1="5" x2="90" y2="5" stroke="blue" fill="transparent" stroke-width="4" id="scrollprogress" />
</svg>

JS:

window.onscroll = function (event) {
   var  offset = window.pageYOffset;
   var  wheight = window.innerHeight;
   var  html = document.documentElement;
   var  docheight = Math.max(document.body.scrollHeight, document.body.offsetHeight, 
                             html.clientHeight, html.scrollHeight, html.offsetHeight);
   var  progress = offset / (docheight - wheight);

   // Give the line a CSS gradient based on scroll position
   document.getElementById("scrollprogress").setAttribute("x2", 90 + progress * 410);
}

演示小提琴

这篇关于滚动时如何填充svg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆