了解如何使用 JavaScript 和 SVG 在滚动条上绘图。
使用 SVG 和 JavaScript 在滚动条上绘制三角形 - 请注意,它必须是 <path> 元素:
<svg id="mySVG">
<path fill="none" stroke="red" stroke-width="3" id="triangle" d="M150 0 L75 200 L225 200 Z"/>
</svg>
<script>
// Get the id of the <path> element and the length of <path>
var triangle = document.getElementById("triangle");
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;
}
</script>
亲自试一试 »
提示: 在我们的 SVG 教程中了解有关 SVG 的更多信息.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!