【问题标题】:stoping a javascript code on pressing shift key在按下 shift 键时停止 javascript 代码
【发布时间】:2014-11-24 11:10:41
【问题描述】:

我正在使用这个 JavaScript 代码移动一些云现在我需要检查用户是否按下了 shift 键 - 当他们按下时,它会停止这个云的动画

我用来移动的代码是:

<script language="javascript">

  function StartMove() {
    var cssBGImage=new Image();
    cssBGImage.src="path to your image.jpg";

    window.cssMaxWidth=cssBGImage.width;
    window.cssXPos=0;
    setInterval("MoveBackGround()",50);
  }

  function MoveBackGround () {
    window.cssXPos=window.cssXPos+1;
    if (window.cssXPos>=window.cssMaxWidth) {
      window.cssXPos=0;
    }
    toMove=document.getElementById("scroller");
    toMove.style.backgroundPosition=window.cssXPos+"px 0px";
  }
</script>

类似这段代码。注意这个对我不起作用

function GetShiftState (event) {
  if (event.shiftKey)
  {
    document.getElementById("myimg").clearTimeout(t);
  }
}

【问题讨论】:

    标签: javascript animation key-events


    【解决方案1】:

    您需要跟踪interval的名称

    MDN

    上查看此相关示例
    var global_cloudInterval;
    
    function StartMove() {
        var cssBGImage=new Image();
        cssBGImage.src="path to your image.jpg";
    
        window.cssMaxWidth=cssBGImage.width;
        window.cssXPos=0;
    
        // Keep track of the interval using a global variable
        // also, don't need to wrap MoveBackGround in quotes
        global_cloudInterval = setInterval(MoveBackGround, 50);
    }
    
    function MoveBackGround () {
        window.cssXPos=window.cssXPos+1;
        if (window.cssXPos>=window.cssMaxWidth) {
            window.cssXPos=0;
        }
        toMove=document.getElementById("scroller");
        toMove.style.backgroundPosition=window.cssXPos+"px 0px";
    }
    
    function GetShiftState (event){
        if (event.shiftKey){
            // now clear the interval using the global variable
            clearInterval(global_cloudInterval);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多