【问题标题】:javascript transform on interval wont work间隔上的javascript转换不起作用
【发布时间】:2020-08-11 15:35:19
【问题描述】:

基本上试图创建一个用户必须单击页面顶部布局的特定单词的游戏,我需要编写 4 个按钮 html 元素以在 div 容器内反弹但是,我的 html 转换间隔不工作。

var upperLimitY = 360;
var lowerLimitY = 0;
var upperLimitX = 520;
var lowerLimitX = 0;
var upperVelocity = 10;
var lowerVelocity = 2;
var velocity = 5;

var wordStore = document.getElementsByClassName("word1")[0];


function startGame() {
  setInterval(moveWord, 10);
}


function moveWord() {

  if (lowerLimitX < wordStore.style.transform.x < upperLimitX && lowerLimitY <
    wordStore.style.transform.y < upperLimitY) {

    wordStore.style.transform = "translate(" + velocity + "px ," + velocity + ")";
    velocity += velocity;
  } else {
    velocity *= -1;
  }
};
<div class="wordGameContainerHeader">
  <h1>Word Wizard</h1>
  <h4>WORD TO FIND</h4>
</div>

<div class="wordGameContainer">
  <button class="word1">WORD 1</button>
  <button class="word2">WORD 2</button>
  <button class="word3">WORD 3</button>
  <button class="word4">WORD 4</button>
</div>

<div>
  <button onclick="startGame()" class="playButton">PLAY</button>
</div>

按钮嵌入在大小为 600px x 300px 的 div 中,元素的宽度为 80px,高度为 40px,这就是为什么我将 x 的上限设置为 600px - 80px,反之亦然限制。正在测试代码的按钮根本不动。

【问题讨论】:

  • 可能是因为没有style.transform.x。你的情况也不会好。

标签: javascript html css


【解决方案1】:

您错过了在moveWord 函数的第二个参数中写入px。我在setInterval 函数中设置了 1 来以慢动作翻译这个词,这样你就可以看到这个词正在翻译。就是这样。

注意:我刚刚检查了为什么您的转换不起作用。我没有检查其他任何内容。

function startGame() {
  setInterval(moveWord, 1000); // use 1s for translating slow.
}

function moveWord() {

  if (lowerLimitX < wordStore.style.transform.x < upperLimitX && lowerLimitY <
    wordStore.style.transform.y < upperLimitY) {

    wordStore.style.transform = "translate(" + velocity + "px ," + velocity + "px)";
    velocity += velocity;
  } else {
    velocity *= -1;
  }
};

【讨论】:

    【解决方案2】:

    语法问题:

    • style.transform 没有子属性(x 和 y)。

    您必须使用 split 或 regex 自己解析它。

    • translate 的 y 部分缺少 px,导致其无效

    wordStore.style.transform = "translate(" + velocity + "px ," + velocity + "px)";

    • 链式条件逻辑(x &lt; y &lt; z)在javascript中无效

    x &lt; y &amp;&amp; y &lt; z

    逻辑问题:

    • 使用您当前的逻辑,按钮将在同一预定义行上弹回
    • 一旦按钮超出范围,您的动作就会停止,因为您在反转velocity 后从未向实际位置添加任何值
    • 您可以像使用id 一样使用class,这很好,但很愚蠢

    基于您的代码的注释示例:

    注意:以全页模式运行

    var upperVelocity = 10;
    var lowerVelocity = 2;
    //var velocity = 5; //REM: Dropped to bring some random dynamic into it
    var speed = 25; //REM: Interval-Timeout
    var bounds = null;
    
    //REM: Calculating the bounds according to the bounds of .wordGameContainer
    //var upperLimitY = 360;
    //var lowerLimitY = 0;
    //var upperLimitX = 520;
    //var lowerLimitX = 0;
    
    //REM: Not required, since there is only one "word1"
    //var wordStore = document.getElementsByClassName("word1")[0];
    
    function startGame(){
      //REM: Calculating the bounds
      bounds = document.querySelector(".wordGameContainer").getBoundingClientRect();
    
      //REM: Getting all .words
      var tListOfWords = document.getElementsByClassName("word");
      for(var i=0, j=tListOfWords.length; i<j; i++){
        //REM: Clearing the current timeout, else speeds up on pressing again
        clearInterval(tListOfWords[i].dataset.Interval);
      
        //REM: x and y require different directions, else they just keep bouncing back and forth diagonally
        tListOfWords[i].dataset.Direction = JSON.stringify({x: 1, y: 1});
      
        //REM: Storing the return of setInterval() to clear it eventually
        //REM: Binding the element instead, so that moveWord() can be used for all words the same
        tListOfWords[i].dataset.Interval = setInterval(moveWord.bind(null, tListOfWords[i]), speed);
        
        //REM: Adding event to stop the movement
        //REM: Using onmouseup to omit keyboard input (tab + enter)
        tListOfWords[i].onmouseup = function(){
          clearInterval(this.dataset.Interval);
          alert(this.id)
        }
      }
    };
    
    //REM: The .word not gets passed as parameter "element"
    function moveWord(element){
      //REM: style.transform has no sub properties
      //REM: Using getBoundingClientRect() so the buttons entirely stay inside the box
      var tPosition = element.getBoundingClientRect(),
          tDirection = JSON.parse(element.dataset.Direction);
    
      //REM Calculate the movement according to upperVelocity and lowerVelocity
      //REM: Using different velocities for x, y to make less predictable and more dynamic
      var tMovementX = Math.floor(Math.random() * (upperVelocity - lowerVelocity) + lowerVelocity),
          tMovementY = Math.floor(Math.random() * (upperVelocity - lowerVelocity) + lowerVelocity);
    
      //REM: Adding the direction of the element
      tMovementX *= tDirection.x;
      tMovementY *= tDirection.y;
    
      //REM: Checking x
      if(
        (tPosition.left + tMovementX) <= bounds.left || 
        (tPosition.right + tMovementX) >= bounds.right
      ){
        tDirection.x *= -1;
        tMovementX *= -1;
        
        //REM: Storing the changed direction
        element.dataset.Direction = JSON.stringify(tDirection)
      };
      
      //REM: Checking y
      if(
        (tPosition.top + tMovementY) <= bounds.top ||
        (tPosition.bottom + tMovementY) >= bounds.bottom
      ){
        tDirection.y *= -1;
        tMovementY *= -1;
        
        //REM: Storing the changed direction
        element.dataset.Direction = JSON.stringify(tDirection)
      };
    
      //REM: Getting the actual left/top assigned to the style
      //REM: Note that those are not the same values as tPosition.
      var tLeftInsideParent = (parseFloat(element.style.left) || 0),
          tTopInsideParent = (parseFloat(element.style.top) || 0);
    
      element.style.left = tLeftInsideParent + tMovementX + "px";
      element.style.top = tTopInsideParent + tMovementY + "px"
    };
    
    //REM: Adjusting the bounds on scrolling and resizing
    window.onscroll = window.onresize = function(){
      //REM: Calculating the bounds
      bounds = document.querySelector(".wordGameContainer").getBoundingClientRect()
    };
    .word{
      position: relative
    }
    
    .wordGameContainer{
      background: #1390ff;
      height: 150px;
      width: 400px;
    }
    <div class="wordGameContainerHeader">
      <h1>Word Wizard</h1>
      <h4>WORD TO FIND</h4>
    </div>
    
    <div>
      <button onclick="startGame()" class="playButton">PLAY</button>
    </div>
    
    <div class="wordGameContainer">
      <!--REM: Why is the "class" used like an "id"? -->
      <button id="word1" class="word">WORD 1</button>
      <button id="word2" class="word">WORD 2</button>
      <button id="word3" class="word">WORD 3</button>
      <button id="word4" class="word">WORD 4</button>
    </div>
    
    Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling..

    【讨论】:

    • 有什么办法可以让按钮不退出容器吗?
    • 这些按钮不会退出我的浏览器中的容器(Chrome、FFox、Edge 的最新版本)。你用的是哪一个?另请注意,只有将 sn-p 置于 全页模式,它才能正确运行。
    • 更改它以计算开始游戏的界限。现在也应该在小型 sn-p 中工作。
    • 老实说,这是令人惊叹的欢呼声,我遇到了一个问题:/ 当我在我的页面上向下滚动时,单词开始在容器外弹跳:/ 在我滚动之前它可以正常工作吗?顺便说一句,很抱歉我一直愿意回复这个冗长的回复,但我发现它令人生畏
    • @Java Lava:可能界限已经搞砸了。我可以看一下,但我想今晚不会了。
    猜你喜欢
    • 1970-01-01
    • 2013-08-14
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多