代码随机停止工作

时间:2016-12-01 11:19:48

标签: javascript html

<img id="myImg" src="http://shushi168.com/data/out/193/37281782-random-image.png" onmouseover="zoomIn()" onmouseout="zoomOut()"> 


function zoomIn(){
        alert("test");
  var element = document.getElementById("myImg");
  var newWidth = 450;
  var newHeight = 200;
  if((element.width != newWidth) && (element.height != newHeight)){
      var zoomStart = function(){
          element.width += 1.5;
          element.height += 1;
          if((element.height < newHeight) && (element.width < newWidth)){
              setTimeout(zoomStart, 10);
          }    
      }
      zoomStart();
  }
  }



function zoomOut(){
      var element = document.getElementById("myImg");
      alert("begin2 " + element.width +" "+ element.height);
      var originalWidth = 300;
      var originalHeight = 100;
      if((element.width != originalWidth) && (element.height != originalHeight)){
          var zoomStart = function(){
              element.width -= 1.5;
              element.height -= 1;
              if((element.height > originalHeight) && (element.width > originalWidth)){
                  setTimeout(zoomStart, 10);
              }      
          }
          zoomStart();
      }
  }

https://jsfiddle.net/j3dgrzaz/1/

请参阅上面的js小提琴我的代码。

当鼠标移过图像时,图像应该放大,当鼠标离开图像时,图像会再次变小。

代码工作正常。我将css移动到一个单独的文件中,代码突然停止工作......

1 个答案:

答案 0 :(得分:0)

您需要在加载页面之前定义javascript函数。所以把它转移到头上它会正常工作。

https://jsfiddle.net/j3dgrzaz/7/

<head>

<script>
function zoomIn(){
        alert("test");
  var element = document.getElementById("myImg");
  var newWidth = 450;
  var newHeight = 200;
  if((element.width != newWidth) && (element.height != newHeight)){
      var zoomStart = function(){
          element.width += 1.5;
          element.height += 1;
          if((element.height < newHeight) && (element.width < newWidth)){
              setTimeout(zoomStart, 10);
          }    
      }
      zoomStart();
  }
  }

  function zoomOut(){
      var element = document.getElementById("myImg");
      alert("begin2 " + element.width +" "+ element.height);
       var originalWidth = 300;
      var originalHeight = 100;
      if((element.width != originalWidth) && (element.height != originalHeight)){
          var zoomStart = function(){
              element.width -= 1.5;
              element.height -= 1;
              if((element.height > originalHeight) && (element.width > originalWidth)){
                  setTimeout(zoomStart, 10);
              }      
          }
          zoomStart();
      }
  }

</script>


</head>