Jquery,如何:首先淡出点击的div,然后是其他人

时间:2013-12-30 23:54:29

标签: javascript jquery html css

HTML

<div id="wrapper">
<div class="test1">
    <img src="x-led.png">
</div>
<div class="test2">
    <img src="x-led.png">
</div>
<div class="test3">
    <img src="x-led.png">
</div>
</div>

JQUERY

<script>
$('#wrapper img').click(function() {
var to = 10000;
var from = 1000;
var number1 = Math.floor(Math.random()*(to-from+1)+from);
var number2 = Math.floor(Math.random()*(to-from+1)+from);
var number3 = Math.floor(Math.random()*(to-from+1)+from);

$('.test1').fadeOut(1000, function() {
    $('.test1').html('You Won: ' + number1).fadeIn(3000);
});
$('.test2').fadeOut(1000, function() {
    $('.test2').html('You Won: ' + number2).fadeIn(3000);
});
$('.test3').fadeOut(1000, function() {
    $('.test3').html('You Won: ' + number3).fadeIn(3000);
});
 });
 </script>

您好。我想问一下如何制作,首先是fadeout和fadein点击DIV,然后是其他div?

也许它可以用循环(for,while)或其他东西做得更紧凑,因为我不认为这样做是正常的。

抱歉,我是javascript的新手,但我是php程序员。

4 个答案:

答案 0 :(得分:1)

嗯,@ Dryden Long的答案对于所提出的问题是可行的,但是一旦我们开始添加更多div,它就会非常深入。另一个解决方案(假设每个div都有一个包含相应数字的data属性。更合适的是,将数字存储在内存对象中而不是将其附加到DOM上)依赖迭代元素的siblings()

var $clickedImg = $(e.target);
var $clickedDiv = $clickedImg.parent();
var $siblings = $clickedDiv.siblings();

$clickedDiv.fadeOut(1000, function () {
    $clickedDiv.html('You Won: ' + $clickedDiv.data('num')).fadeIn(3000, function () {
        $siblings.each(function (i, e) {
            var $sib = $(e);
            $sib.fadeOut(1000, function () {
                $sib.html('You Won: ' + $sib.data('num')).fadeIn(3000);
            });
        });
    });
});

请参阅http://jsfiddle.net/Palpatim/qk4Ba/了解演示。

答案 1 :(得分:0)

要按顺序运行您的功能,请将代码更改为:

$('.test1').fadeOut(1000, function() {
    $('.test1').html('You Won: ' + number1).fadeIn(3000, function () {
        $('.test2').fadeOut(1000, function() {
            $('.test2').html('You Won: ' + number2).fadeIn(3000, function () {
                $('.test3').fadeOut(1000, function() {
                    $('.test3').html('You Won: ' + number3).fadeIn(3000);
                });
            });
        });
    });
}); 

用于此的术语是callback本质上,jQuery运行第一个函数,一旦完成,第二个函数开始,依此类推。

答案 2 :(得分:0)

这是我的解决方案。它会根据你拥有的许多测试格式进行扩展,并且会从原始点击开始按顺序淡出和淡出。

HTML:

<div id="wrapper">
 <div class="test1"><img src="x-led.png"></div>
 <div class="test2"><img src="x-led.png"></div>
 <div class="test3"><img src="x-led.png"></div>
</div>

JS / JQuery的:

var winMin = 1000;
var winMax = 10000;
function fadeAfterSequence(element) {
 element.fadeOut(1000, function() {
  var winAmmt = Math.floor(Math.random() * (winMax - winMin + 1) + winMin);
  element.html('You Won: ' + winAmmt);
  element.fadeIn(1000, function() {
   fadeAfterSequence(element.next());
  });
 });
}
$(document).on('ready', function() {
 $('#wrapper img').on('click', function() {
  fadeAfterSequence($(this).parent());
 });
});

工作小提琴演示: http://jsfiddle.net/6RsVD/

答案 3 :(得分:-1)

我对编码不满意,但我建议你不要使用.fadeOut()或.fadeIn()函数来查看.toggle()

尝试查看文档:{​​{3}}

相关问题