当我将鼠标悬停在图像上时,我希望它不断扩大,直到我不再使用鼠标

时间:2015-11-20 03:17:03

标签: javascript html

我知道这段代码是错误的(具体是while循环)。我想知道如何继续放大图像(id ="图像")我将鼠标放在它上面。我现在拥有它,所以当我将鼠标悬停在图像上时,它会放大一次。当我停止使用鼠标时,它会回到原来的大小。有什么帮助吗?

这是我的代码:

<!DOCTYPE HTML>
<html>
    <head>
        <title></title>
    </head>

    <body>
        <img onmouseover="enlarge()" onmouseout="decrease()" height="100" width="100" src="http://www.mariowiki.com/images/thumb/5/57/Powerup-mini-mushroom-sm.png/200px-Powerup-mini-mushroom-sm.png" id="image">
        <script>

            function enlarge() {
                var image = document.getElementById('image');
                if(image && image.style) {
                    while(onmouseover = document.getElementById('image')){
                        image.style.height = '200px';
                        image.style.width = '200px';    
                    }
                }
            }

            function decrease(){
                var image = document.getElementById('image');
                if(image && image.style) {
                    image.style.height = '100px';
                    image.style.width = '100px';
                } 
            }


        </script>
    </body>
</html 

1 个答案:

答案 0 :(得分:0)

您可以使用setInterval代替while按某个时间间隔执行某些操作。第二个参数代表以毫秒为单位的近似时间间隔 - 在我的例子中它是13 - 0.013秒。 然后,您可以使用clearInterval停止执行它。

&#13;
&#13;
var increaseInterval;

function enlargeStep() // one step of enlarging
{
    document.getElementById('image').width += 1;
    document.getElementById('image').height += 1;
}

function enlarge()
{
  increaseInterval = setInterval(enlargeStep, 13); // start doing steps every 13ms
  enlargeStep(); // do it right now, so that effect is seen immediately
}

function decrease()
{
  clearInterval(increaseInterval); // stop executing these steps
  document.getElementById('image').height = 100; // reset values
  document.getElementById('image').width = 100;
}
&#13;
<img onmouseover="enlarge()" onmouseout="decrease()" height="100" width="100" src="http://www.mariowiki.com/images/thumb/5/57/Powerup-mini-mushroom-sm.png/200px-Powerup-mini-mushroom-sm.png" id="image">
&#13;
&#13;
&#13;

但是,如果你想制作流畅的动画,那么你可能会对jQuery库的.animate()方法感兴趣:

&#13;
&#13;
function enlarge()
{
  $("#image").animate({
      'height': '300px',
      'width': '300px'
  });
}

function decrease()
{
  $("#image").animate({
      'height': '100px',
      'width': '100px'
  });
}
&#13;
#image {
    height: 100px;
    width: 100px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img onmouseover="enlarge()" onmouseout="decrease()" src="http://www.mariowiki.com/images/thumb/5/57/Powerup-mini-mushroom-sm.png/200px-Powerup-mini-mushroom-sm.png" id="image">
&#13;
&#13;
&#13;