在我目前正在构建的网站上,有一条SVG路径,它基本上是一条直线。当用户向下滚动页面时,该路径会绘制下来,直到用户触底。
我使用的代码是从这个页面中获取的:https://www.w3schools.com/howto/howto_js_scrolldrawing.asp 代码如下:
我使用的代码是从这个页面中获取的:https://www.w3schools.com/howto/howto_js_scrolldrawing.asp 代码如下:
<svg style="min-height: 113.5%;" version="1.1" id="line_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="4px" height="113.5%" xml:space="preserve">
<path style="max-height: 113.5%;" id="blue_line" fill="freeze" stroke-width="4" stroke="#3b7fdc" d="M0 0 v2884 400" />
</svg>
<script>
// Get the id of the <path> element and the length of <path>
var triangle = document.getElementById("blue_line");
var length = triangle.getTotalLength();
// The start position of the drawing
triangle.style.strokeDasharray = length;
// Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw
triangle.style.strokeDashoffset = length;
// Find scroll percentage on scroll (using cross-browser properties), and offset dash same amount as percentage scrolled
window.addEventListener("scroll", myFunction);
function myFunction() {
var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
var draw = length * scrollpercent;
// Reverse the drawing (when scrolling upwards)
triangle.style.strokeDashoffset = length - draw;
}
这个方法非常好用,但是目前当用户向上滚动页面时,SVG路径会随之“逆转”回到上面。我希望的效果是SVG只能在页面上绘制,并且在用户向上滚动页面时不会逆转。
有没有人知道如何编辑上面的脚本来实现这种期望的行为?