如何使用javascript为html过渡添加淡入淡出效果

时间:2015-08-10 16:00:35

标签: javascript jquery html css transition

我有这段代码(见下面的jsfiddle)

<script type='text/javascript'> https://jsfiddle.net/mA8hj/并想知道如何编辑javascript,方法是点击小提琴中的链接,当点击另一个链接时,显示的文字会缓慢淡入另一个文本。 (通过添加-ms-transition来改变你在CSS中使用的东西:.2s;)。

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试将"slow"/"fast"/"medium"/any delay in milliseconds作为参数传递给show

$('[class^="question"]').on('click', function(e){
    e.preventDefault();
    var numb = this.className.replace('question', '');
    $('[id^="answer"]').hide();
    $('#answer' + numb).stop().show("slow");
});

DEMO

或使用.fadeIn()

$('[class^="question"]').on('click', function(e){
    e.preventDefault();
    var numb = this.className.replace('question', '');
    $('[id^="answer"]').hide();
    $('#answer' + numb).css("opacity",0).stop().fadeIn("slow");
});

答案 1 :(得分:0)

使用CSS类和CSS转换,并仅使用jQuery添加/删除此类.show

$('[class^="question"]').on('click', function(e){
    e.preventDefault();
    var numb = this.className.replace('question', '');
    $('[id^="answer"]').removeClass("show");
    $('#answer' + numb).addClass("show");
});
#answer,
#answer1,
#answer2,
#answer3,
#answer4 {
  position: absolute;
  opacity: 0;
  transition-duration: 0.4s;
}
#answer.show,
#answer1.show,
#answer2.show,
#answer3.show,
#answer4.show {
  position: absolute;
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="new_member_box"> 
    <a href="#" class="question1"><h4>Vision</h4></a>
</div>

<div class="new_member_box"> 
    <a href="#" class="question2"><h4>Church History</h4></a>
</div>

<div class="new_member_box"> 
    <a href="#" class="question3"><h4>Becoming a Member</h4></a>
</div>
<div class="new_member_box"> 
    <a href="#" class="question4"><h4>Pastor-in-Training</h4></a>
</div>

<div class="clear" class="question"></div>

<div id="answer1">1</div>
<div id="answer2">2</div>
<div id="answer3">3</div>
<div id="answer4">4</div>

<div class="new_member_box_display show" id="answer">Text will appear here when one of the tabs above is clicked</div>

https://jsfiddle.net/mA8hj/94/