使用JavaScript触发CSS转换

时间:2016-05-03 23:55:43

标签: javascript html css

我在学习JavaScript并遇到一个简单的问题: 当其他元素仅通过JavaSript悬停时,我想触发一个CSS动画(旋转蓝色螺母)。

这是我到目前为止所做的事情,而且我不知道我在这个片段中遗漏了什么:



$('#menu').hover(
  function () {
    $('#nut').addClass('spin');
  },
  function () {
    $('#nut').removeClass('spin');
  }
);

#nut {
    transform-origin: center center;
    transform-style: preserve-3D;
    transition: all 1s ease;
}

.spin {
  transform: rotate(180deg);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg id="menu" x="0px" y="0px" width="71.39px" height="71.39px" viewBox="0 0 71.39 71.39" enable-background="new 0 0 71.39 71.39" xml:space="preserve">
  <polygon id="nut" fill="#0000ff" points="66.605,53.541 35.694,71.388 4.784,53.541 4.784,17.849 35.694,0.002 66.605,17.849"/>
</svg>
&#13;
&#13;
&#13;

非常感谢你的帮助!提前谢谢!

1 个答案:

答案 0 :(得分:4)

唯一缺少的是jquery。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<svg id="menu" x="0px" y="0px" width="71.39px" height="71.39px" viewBox="0 0 71.39 71.39" enable-background="new 0 0 71.39 71.39" xml:space="preserve">
  <polygon id="nut" fill="#0000ff" points="66.605,53.541 35.694,71.388 4.784,53.541 4.784,17.849 35.694,0.002 66.605,17.849"/>
</svg>

看一下这里的代码:

https://jsfiddle.net/j2bon1gc/

实际上它不仅缺少Jquery,而且为了工作它特别缺少大于2.2的jquery版本,这是实现此功能的版本。

看看这里:jQuery SVG, why can't I addClass?

在我打开的Meta问题中:Why isn't jQuery working in this question's code snippet?