使用单击功能淡入/淡出文本

时间:2014-08-31 10:49:54

标签: jquery html image

我打算做的是fadeIn和fadeOut的一些段落,并为每个要隐藏的点击事件添加一个点击事件,并为fadeIn添加一个图像几秒钟,之后图像为fadesOut,段落淡出。

我设法这样做了,但这是我编写的一个非常混乱的脚本,我确信它可以在我编写的一半以上的代码中完成,但我不知道如何,这就是我需要你们的地方。

任何人都可以尝试优化我的代码(如果“你”有耐心,请解释一下你是如何以及为什么要做你正在做的事情),请记住:

*第一段是第一张图片,第二张图片是secont p,依此类推。 *我必须能够为每张图像显示不同的秒数。

工作但很冗长jsFiddle

HTML:

<div id="help">
<p class="helper" id="1">Do you...?</p>
<p class="helper" id="2">Do you still...?</p>
<p class="helper" id="3">Do you really still...?</p>
</div>

<div class="image1"></div>
<div class="image2"></div>
<div class="image3"></div>

SCRIPT:

(function() {

    var helper = $(".helper");
    var helperIndex = -1;

    function showNextHelp() {
        ++helperIndex;
        helper.eq(helperIndex % helper.length)
            .fadeIn(500)
            .delay(1000)
            .fadeOut(500, showNextHelp);
    }

    showNextHelp();

})();

$("#1.helper").click(function(){

    $("#help").fadeOut(500);
    $(".image1").fadeIn(500);

    setTimeout(function() {
        $('.image1').fadeOut(500);
        $("#help").fadeIn(500);
    }, 500);

});
$("#2.helper").click(function(){

    $("#help").fadeOut(500);
    $(".image2").fadeIn(500);

    setTimeout(function() {
        $('.image2').fadeOut(500);
        $("#help").fadeIn(500);
    }, 700);

});
$("#3.helper").click(function(){

    $("#help").fadeOut(500);
    $(".image3").fadeIn(500);

    setTimeout(function() {
        $('.image3').fadeOut(500);
        $("#help").fadeIn(500);
    }, 800);

});

1 个答案:

答案 0 :(得分:1)

您可以将三个 .helper 类事件合并为一个。选择器的ID可以帮助您。

<p class="helper" data-timeout-value="500" id="1">Do you...?</p>
<p class="helper" data-timeout-value="700" id="2">Do you still...?</p>
<p class="helper" data-timeout-value="800" id="3">Do you really still...?</p>

var $timeoutVariable;
$(".helper").click(function(){
   var $this = $(this),
       $id = $this.attr('id'),
       $timeout = $this.attr('data-timeout-value');

   $("#help").fadeOut(500);
   $(".image"+$id).fadeIn(500);
   $this.addClass('processing');

   clearTimeout($timeoutVariable);
   $timeoutVariable = setTimeout(function() {
      $('.image'+$id).fadeOut(500);
      $("#help").fadeIn(500);
      $this.removeClass('processing');
   }, $timeout);
});

希望它有所帮助。

问候。