如果不适用于所有语句,则为Javascript else

时间:2015-04-02 18:08:28

标签: javascript jquery html

当用户从选择菜单中选择一个值时,我希望javascript使div上下滑动更快或更慢。 JavaScript根本不起作用。我怎么能用if/ else if使div滑动更快/更慢 功能?

HTML:

<p class="explanation">
This snippet will show you how to make the <i>Bouncing Div</i> animation, using <a href="http://jquery.com" target="_blank">Jquery</a> and <a href="http://jqueryui.com" target="_blank">Jquery UI</a><br>Click <a href="http://api.jquery.com" target="_blank">here</a> to familiarize yourself with Jquery. 
</p>

<p class="explanation">
Click <button>here</button> to start the animation on the below div.
</p>
Select your speed here:
<select id="select-speed">
<option value="">Select speed</option>
<option value=".5x">.5x</option>
<option value="1x">1x</option>
<option value="2x">2x</option>
</select>
then click the button above.
<div class="experiment-div">

</div>

JS:

var ex = $('.experiment-div');
$('.experiment-div').show();

var starter = $('button');
var stopper = $('input[type=button]');
var i = 0;
var select = $('#select-speed').val();
starter.click(function () {
    while (i < 1000) {
        ex.slideUp(2000).slideDown(2000);
        i++;
    }
    if (select == '1x') {
        while (i < 1000) {
            ex.slideUp(2000).slideDown(2000);
            i++;
        }
    } else if (select == '.5x') {
        while (i < 1000) {
            ex.slideUp(4000).slideDown(4000);
            i++;
        }
    } else if (select == '2x') {
        while (i < 1000) {
            ex.slideUp(1000).slideDown(1000);
            i++;
        }
    }
    ex.append('<p>Cool, huh?</p><p>More coming soon!</p>');
});

我只是做错了吗?

1 个答案:

答案 0 :(得分:0)

看起来你很可能不会链接jQuery。

您需要添加以下内容:

<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>

取消注释演示的第一行,看它是否有效。

演示JSFiddle


修改

我又看了一眼。我被评论说:“javascript根本不起作用。”它确实有效,但不正确。问题是while循环在队列中放置了1000个动画。尽管if/else if语句正在运行,但新动画甚至更进一步。我重写了脚本以使用.stop()来清除队列,我认为这正是你要找的。

JS:

var ex = $('.experiment-div');
$('.experiment-div').show();

var starter = $('button');
var stopper = $('input[type=button]');

function animateDiv(speed) {
    var i = 0;
    while(i < 1000) {
        i++;
        ex.slideUp(speed).slideDown(speed);
    }
}

starter.click(function() {
    ex.stop(true,true);
    var select = $('#select-speed').val();
    ex.append('<p>Cool, huh?</p><p>More coming soon!</p>');
    if (select == '1x') {
        animateDiv(2000);
        console.log('fired 1x');
    } else if (select == '.5x') {
        animateDiv(4000);
        console.log('fired .5x');
    } else if (select == '2x') {
        animateDiv(1000);
        console.log('fired 2x');
    } else {
        console.log('error');
    }
});

新演示JSFiddle