旋转一个div元素onmouseenter并停止旋转onmouseleave

时间:2014-02-02 17:34:51

标签: javascript html css

我搜索了很多,但我无法理解实施(我是初学者)。所以请帮助我。

   <div id="card" style="height:100;width:100;background-color:blue" 
          onmouseenter="start('1')" onmouseleave="start('0')"  >

   </div>

的javascript:

     var x=0;
     var y;
     function start(d)
    {
       if(d=='1')
          y=setInterval(function(){rotate()},10);
       else
       {
        clearInterval(y);
       }

   }
   function rotate()
   {
      x+=1;
      x=x%360;
      document.getElementById("card").setAttribute("style","-webkit- 
            transform:rotateX("+x+"deg)");
   }

这里我试图旋转div元素onmouseenter并停止旋转onmouseleave但它无法正常工作

2 个答案:

答案 0 :(得分:1)

您正在覆盖卡片的原始样式,导致卡片消失。我建议你不要使用内联样式,这是一个不好的做法。您还遇到错误:height:100;width:100;。与标记属性不同,高度和宽度的CSS属性需要有一个单位,因此height:100px; width:100px;是可以的。

document.getElementById("card")
    .style["-webkit-transform"] = "rotateZ(" + x + "deg)";

以下是您的代码的工作版本(请注意,我将旋转更改为Z轴,它更有意义):http://jsfiddle.net/34JKj/1/

另一个想法:您还可以使用CSS定义无限旋转动画,将其绑定到某个类,然后在鼠标进入/离开时添加/删除该元素。 CSS比JS表现更好,并且已经成为一种标准,因此值得思考。

答案 1 :(得分:1)

<强> LIVE DEMO

HTML:

<div id="card"></div>

CSS:

#card{
  height:100px;
  width:100px;
  background:blue;
}

JS:

var x=0;
var y;
var $card = document.getElementById("card");

function start(){
      y = setInterval(rotate,25);
}
function stop(){
   clearInterval(y);
}

function rotate(){
   $card.setAttribute(
     "style","-webkit-transform:rotate("+ (++x % 360) +"deg)"
   );
}

$card.addEventListener('mouseenter', start, false);
$card.addEventListener('mouseleave', stop, false);