在javascript中更改文本时如何添加淡入和淡出 [英] How to add fade in and fade out when changing between texts in javascript
问题描述
我下面有我的JAVASCRIPT代码,该代码每2.5秒在2个单词之间转换一次,我想为它使用的数组中的单词之间的过渡添加淡入淡出.我知道我需要使用Jquery,但是如何在此递归函数中实现它呢?有什么想法吗?
I have below my JAVASCRIPT code which change between 2 words every 2.5 seconds and I want to add fading to the transition between the words in the array it uses. I know that I need to use Jquery but how do I implement it in this recursive function? Any ideas?
HTML
<h2 id="changeText">Data Scientist</h2>
JAVASCRIPT
JAVASCRIPT
<script type="text/javascript">
var text = ["first","second"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 2500);
function change() {
elem.innerHTML = text[counter];
counter++;
if(counter >= text.length) { counter = 0; }
}
</script>
CSS
.banner-right h2{
font-size: 50px;
font-weight: 300;
color: #ffffff;
margin: 15px 0 45px 0;}
推荐答案
由于您使用的是Native JavaScript,因此可以使用CSS过渡和classList
.
Since you are using Native JavaScript you could use CSS transitions and classList
.
类似的东西:
CSS
#changeText {
opacity: 1;
transition: opacity 0.5s;
}
.hide {
opacity: 0 !important;
}
JavaScript
JavaScript
function change() {
elem.classList.add('hide');
setTimeout(function () {
elem.innerHTML = text[counter];
elem.classList.remove('hide');
counter++;
if (counter >= text.length) {
counter = 0;
}
}, 500);
}
jsFiddle: http://jsfiddle.net/nt97pazr/
注意:我在CSS中使用了!important
,因为当将opacity: 1;
与ID选择器一起应用时,其优先级高于类选择器.
jsFiddle: http://jsfiddle.net/nt97pazr/
Note: I used !important
in the CSS because opacity: 1;
when applied with a ID selector has priority over a class selector.
这篇关于在javascript中更改文本时如何添加淡入和淡出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!