使用jquery后,在::上复制CSS动画

时间:2018-03-10 15:56:43

标签: javascript jquery html css

所以我做了很多搜索,似乎无法找到另一个有帮助的问题。但是我觉得这可能是一个常见的问题,所以无论如何都可能是重复的。

当我悬停一段文字时,我有一个非常好的CSS下划线动画,你可以看到这里的例子:



let options = ['Over Here', 'This Way', 'At Me']

$(document).ready(function () {
  let jobInterval = setInterval(() => changeText(), 3000)
})

function changeText () {
  let newText = options[Math.floor(Math.random() * options.length)]
  $('#change').text(newText)
}

#change {
    display: inline-block;
    position: relative;
    padding-bottom: 3px;
}
#change:after {
    content: '';
    display: block;
    margin: auto;
    height: 3px;
    width: 0px;
    background: transparent;
    transition: width 3s ease, background-color 3s ease;
}
#change:hover:after {
    width: 100%;
    background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h1>
    <span>Look </span>
    <span id="change">Over Here</span>
  </h1>
</div>
&#13;
&#13;
&#13;

https://jsfiddle.net/6b2cqrj7/7/

然而,当我悬停时,我不希望它完成。这个想法是我有一段文字每X秒都会改变一次,我想让下划线动画X秒,然后单词切换,动画再次播放。就像一个小计时器吧。

我尝试了各种各样的方法,但因为我无法使用JS / JQuery操作:: after标签,所以我无法解决如何使其工作的问题。 因为动画发生在:: after标签上,所以我不能只添加一个我需要更改CSS值的新类,因此转换将适用。我想。

这是我第一次尝试使用CSS动画,所以我在这里很难过。

1 个答案:

答案 0 :(得分:2)

使用CSS3 keyframes获得所需的结果。

&#13;
&#13;
let options = ['Over Here', 'This Way', 'At Me']

$(document).ready(function () {
  let jobInterval = setInterval(() => changeText(), 3000)
})

function changeText () {
  let newText = options[Math.floor(Math.random() * options.length)]
  $('#change').text(newText)
}
&#13;
#change {
    display: inline-block;
    position: relative;
    padding-bottom: 3px;
}
#change:after {
    content: '';
    display: block;
    margin: auto;
    height: 3px;
    width: 0px;
    background: transparent;
    animation: myLine 3s ease infinite;
    transition: width 3s ease, background-color 3s ease;
}
#change:hover:after {
    width: 100%;
    background: red;
}

@keyframes myLine{
  from {width: 0; background: transparent;}
  to {width: 100%; background: red;}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h1>
    <span>Look </span>
    <span id="change">Over Here</span>
  </h1>
</div>
&#13;
&#13;
&#13;

希望这有帮助