使用外部 javascript 文件触发 HTML-class

Trigger a HTML-class with external javascript file



我在我的网页上使用这些图标:http://fontawesome.io/examples/
他们用于图标的一种预设 class 是 fa-spin,它会使图标旋转(du-uh)。
我想让图标在悬停时旋转。 我的 HTML 片段(class "fa fa-envelope" 触发图标本身):

<a href="http://google.com" class="navbar-item">                
    <span class="icon">
        <i id="wantspin" class="fa fa-envelope fa-spin" onmouseover="dothis()"></i>
    </span>
</a>


必须通过函数 onmouseover 以某种方式触发 fa-spin-class,对吗?

这是我的 javascript 代码,我知道我还没有做任何事情,除了将 <i>id 与变量 x 链接起来,但我有点迷路了。

function dothis() 
{
var x = document.getElementById ("wantspin")
} 


我希望它是有道理的,你明白了问题。我感谢任何帮助、见解、提示和技巧,谢谢。

您可以从 font awesome 的样式表中获取 fa-spin 规则并添加一个 :hover 选择器:

.spin:hover {
    -webkit-animation: fa-spin 2s infinite linear;
    animation: fa-spin 2s infinite linear
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<a href="http://google.com" class="navbar-item">
    <span class="icon">
        <i class="fa fa-envelope spin"></i>
    </span>
</a>

Chris G 的回答更好。这是与您尝试做的事情相同的另一个答案。更好的方法是查看 jquery 并改用不显眼的事件处理程序。

您可以忽略我的 HTML,它就在那里,因此 javascript 示例有效。

function dothis() {
  var el = document.getElementById('wantspin');
  if (el) {
    el.classList.add('fa-spin');
  }
}

function dothat() {
  var el = document.getElementById('wantspin');
  if (el) {
    el.classList.remove('fa-spin');
  }
}
#wantspin {
  height: 20px;
  width: 20px;
  background: blue;
}

.fa-spin {
  border: 3px solid red;
}
<a href="http://google.com" class="navbar-item">
  <span class="icon">
        <div id="wantspin" class="fa fa-envelope" onmouseover="dothis()" onmouseout="dothat()"></div>
    </span>
</a>

要做到这一点,只需在 javaScript 中添加和删除 class 并向您的元素添加一个 onmouseout 函数。你的 html 将是这个(注意没有 fa-spin class)。

<a href="http://google.com" class="navbar-item">
    <span class="icon">
        <i id="wantspin" class="fa fa-envelope" onmouseover="dothis()" onmouseout="stopthis(this)"></i>
    </span>
</a>

还有你的javascript.

function dothis() {
    var x = document.getElementById("wantspin");
    x.classList.add("fa-spin");
} 
function stopthis() {
    var x = document.getElementById("wantspin");
    x.classList.remove("fa-spin");
}