简体   繁体   English

jQuery带淡入淡出效果的DIVS

[英]jQuery switvching DIVS with fade effect

I have a very simple script to switch out divs. 我有一个非常简单的脚本来切换div。 I would like to add in a fading transition to the script so that it is a bit smoother. 我想在脚本中添加淡入淡出的过渡效果,以使其更加流畅。 However I cannot see what I am doing wrong (totally JS incompetent) Thanks for any advice. 但是,我看不到自己在做错什么(完全没有JS能力)。谢谢您的建议。

  jQuery(document).ready(function( $ ) {

$('#div2, #div3').hide();

$('.show').click(function () {

    $('.targetDiv').hide().fadeOut(1000);

    $('#div' + $(this).attr('target')).show();

});

});

Your problem lies in this line: $('.targetDiv').hide().fadeOut(1000); 您的问题出在这行: $('.targetDiv').hide().fadeOut(1000);
What is does - it sets style display: none; 是什么-它设置样式display: none; to all your elements you plan to cross-fade. 您打算交叉淡入淡出的所有元素。

Also use the right attributes: data-target="#div1" instead of target="#div1" (which is not used for that purpose) 还要使用正确的属性: data-target="#div1"而不是target="#div1" (不用target="#div1"目的)

Instead: 代替:

 jQuery(function($) { // DOM ready // get all your targetDiv elements var $fadeDivs = $(".targetDiv"); // Hide all but this one $fadeDivs.not("#div1").hide(); $('.show').click(function(evt) { // prevent the browser doing default stuff evt.preventDefault(); // get the target element - using data-target attribute! var selector = $(this).data('target'); var $target = $( selector ); // crossfade (don't forget to use .stop()) $fadeDivs.not($target).stop().fadeOut(1000); $target.stop().fadeIn(1000); }); }); 
 .targets{ position:relative; height:100px; } .targetDiv { position:absolute; height:100px; top:0; left:0;} 
 <div class="targets"> <div id="div1" class="targetDiv"><img src="//placehold.it/100x100/0bf"></div> <div id="div2" class="targetDiv"><img src="//placehold.it/100x100/f0b"></div> <div id="div3" class="targetDiv"><img src="//placehold.it/100x100/bf0"></div> </div> <a data-target="#div1" class="show">SHOW1</a> <a data-target="#div2" class="show">SHOW2</a> <a data-target="#div3" class="show">SHOW3</a> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM