2017-09-22 32 views
0

我正在尝试制作滚动动画,当您滚动时,svg行的x2点将为之前值的50%。在滚动中不断缩小SVG长度

比方说,你开始在X2 = 100,你做一个onscroll功能,然后在滚动时,你将有一个x2 = 50, 25, 12.5...

,行会收缩少快。

这是我到目前为止有:

<body onscroll="myFunction()"> 
    <svg id=l ine height="50" width="100%"> 
    <line id = horLine x1="0" y1="0" x2="100%" y2="0" style="stroke:rgb(255,0,0);stroke-width:2" /> 
    </svg> 
</body> 
<script> 
    function myFunction() { 
    (? ? ?) 
    } 

我不知道的JavaScript,这将是什么。

我假设我应该创建一个变量,然后在每次函数运行时减半该变量值。

我似乎无法弄清楚。

回答

0

使用jQuery:

var x2 = $('#horLine').attr('x2').slice(0, -1); 
 
// .slice(0, -1) is used to remove the '%' from the attribute 
 

 
$(document).scroll(function() { 
 
    x2 *= 0.99; 
 
    $('#horLine').attr('x2', x2 + '%'); 
 
});;
svg { position: fixed;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<svg id="line" height="50" width="100%"> 
 
<line id="horLine" x1="0" y1="0" x2="100%" y2="0" style="stroke:rgb(255,0,0);stroke-width:2" /> 
 
</svg> 
 
<div style="height: 1000000px;"> 
 
</div>

我没有做到50%,但是99%,这样你就可以看到效果。

您可以通过检测改善行为向上/向下滚动等

+0

假设他正在使用jQuery。 – Confuzing

0

如果X2是一个百分数它是一个稍微复杂一些,但你可以通过ID基于当前值获取元素然后将其设置的x2。

所以,你的功能会是这样的:

var x2 = document.getElementById("horLine").getAttribute("x2").match(/\d+/)[0]/2 + "%"; 
document.getElementById("horLine").setAttribute("x2", x2); 

你也可以使用subtring而不是match删除百分号。不确定哪个更有效。