【问题标题】:Increment is not working correctly in for loop [duplicate]增量在 for 循环中无法正常工作 [重复]
【发布时间】:2019-11-16 06:39:40
【问题描述】:

Js 将 for 循环中的i+=2 读取为

4002

而不是添加应为4022+400。增量不在引号中,所以我不知道它为什么这样做。

function move(evt) {
  var text = evt.target;
  var currentSize = text.getAttribute("font-size");
  var timer = 0;
  for (let i = currentSize; i < 11000; i += 2) {
    function changeText() {
      text.setAttribute("font-size", i);
      console.log(i);
    }
    setTimeout((changeText), timer);
    timer = timer + 40;
  }
.container {
  background-color: yellow;
  z-index: 7;
  height: 100%;
  width: 100%;
  position: absolute;
  opacity: .5;
}
<div class="container">
  <svg height="100%" width="100%">
            <text onclick="move(evt)" dx="0%" dy="50%" font-size="400">This is my Journey
            </text>
        </svg>
  </container>

【问题讨论】:

  • i 必须是字符串,而不是数字。 text.getAttribute("font-size") 是否返回字符串?
  • 使用var currentSize = parseInt(text.getAttribute("font-size"))var currentSize = parseFloat(text.getAttribute("font-size"))。感谢@Carcigenicate。
  • 我做了一个 sn-p 但没有修复语法问题...
  • 这对我来说似乎是 stackoverflow.com/a/15195345/125981 的副本。

标签: javascript html css svg


【解决方案1】:

正如@Carcigenicate 和@collapsar 在cmets 上所说的那样;尝试将 currentSize 解析为数字。

  function move(evt) {
    var text = evt.target;
    var currentSize = parseInt(text.getAttribute("font-size")); // <- Parse the currentSize as int
    var timer = 0;
    for (let i = currentSize; i < 11000; i += 2) {
      function changeText() {
        text.setAttribute("font-size", 58);
        console.log(i);
      }
      setTimeout((changeText), timer);
      timer = timer + 40;
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 2020-10-27
    相关资源
    最近更新 更多