0

我一直在将 div 框从 a 移动到 b 然后再返回时遇到问题。当鼠标离开 div 框时,我还需要它返回开始位置。到目前为止,这是我想出的。

<div id="tank" style=" width:344px; height:300px;
 background-image:url('images/warning2.png');
 box-shadow:0px 0px 100px;
 ;border-radius:20px; position:relative; left:-180px; top:10px;">
 </div>


 <script type="text/javascript">

 document.getElementById('tank').onmouseover = function() {
 var elem = this, 
 pos = -180,

 timer = setInterval(function() {
 pos--;
 elem.style.left = pos+"px";
 if( pos == 500) clearInterval(timer) ;
 document.getElementById('plane').onmouseover = null;
 },1);
 };
4

2 回答 2

0

如果可以使用jQuery,则可以执行以下操作:

$("#tank").hover(
  function () {
    $(this).animate({
        left: '-=180'
    });
  }, 
  function () {
    $(this).animate({
        left: '+=180'
    });
  }
);​

http://jsfiddle.net/charlescarver/QgF2h/

于 2012-09-07T23:03:53.730 回答
0

你的位置从-180开始,你的最终位置是+500。但是你正在减少位置变量的值,所以它永远不会达到 500。

至于重新退出鼠标,您应该执行以下操作:

var timer = null;
var tank = document.getElementById('tank');

function animate(elem, target)
{
    var pos = parseInt(elem.style.left.replace(/[^0-9\-]/g, ""));

    clearInterval(timer);
    timer = setInterval(function()
    {
        elem.style.left = (pos += pos < target ? 1 : -1) + "px";
        if(pos == target) clearInterval(timer) ;
    }, 1);
}

tank.addEventListener("mouseover", function()
{
    animate(this, 500);
}, false);

tank.addEventListener("mouseout", function()
{
    animate(this, -180);
}, false);

​</p>

于 2012-09-07T23:24:56.607 回答