如何将一条竖直线水平移动并支持“暂停”和“继续”移动(涉及IT技术)。

3
我想把一条竖线向水平方向移动,并支持“暂停”和“继续”移动。当我点击“暂停”按钮时,线会停止移动;当点击“继续”时,线会继续移动。
现在,我使用“transition”函数来实现从左到右的水平过渡,但不知道如何“暂停”和“继续”。
这是我的演示:
<html>
<head>
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
  <svg width="500" height="500">
    <line x1="100" y1="0" x2="100" y2="100" stroke="black"/>
  </svg>
</body>

<script>
  d3.select("line").transition()
    .ease(d3.easeLinear)
    .duration(2000)
    .attr("x1",200)
    .attr("x2",200);
</script>
</html>

是否有可能“暂停”过渡,或者如何在不使用“transition”函数的情况下实现此目标?

1个回答

2
这是一种实现方法:

这是一种实现该目标的方法:

<html>
<head>
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>

  <div class="control-buttons">
    <button class="pause">
      Pause
    </button>
    <button class="continue">
      Continue
    </button>    
  </div>
  <svg width="1000" height="500">
    <line x1="100" y1="0" x2="100" y2="100" stroke="black"/>
  </svg>
</body>

<script>   
  // pause
  d3.select('button.pause').on('click', function() {
   d3.select("line").interrupt();
  });
  
  d3.select('button.continue').on('click', function() {
   d3.select("line").transition()
      .ease(d3.easeLinear)
      .duration(10000)
      .attr("x1",800)
      .attr("x2",800);
  }).dispatch('click');
  
</script>
</html>

您应该寻找的是 d3-transition-interrupt。 我已将其用于“暂停”按钮和“继续”按钮,只需重新启用相同的过渡即可。 要开始转换,请按继续按钮。

这只是一个基本版本,但我希望逻辑足够清晰。 希望这有所帮助。


是的,它有帮助。你能解释一下 'dispatch' 函数吗?我尝试了这段代码并发现如果没有使用 'dispatch' 它就无法在开头运行。所以 'dispatch' 与此有关。但在查找文档后,我仍然不是很清楚 'dispatch' 到底做了什么。 - Marbo
dispatch 只是在页面加载时触发“继续”按钮的点击事件。如果您观察,我将所有的过渡代码都移动到了“click”事件中。 - Shashank

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接