0

JavaScript:

var classes = ['a', 'b', 'c'];
$(window).scroll(function() {
    if ($(window).scrollTop() > 20) {
        var cls = classes[Math.floor( Math.random() * classes.length )];
        $('#box').toggleClass(cls);
    }
});

CSS:

.a {
    background: red;
    height: 100px;
}
.b {
    background: green;
    height: 200px;
}
.c {
    background: blue;
    height: 300px;
}

DEMO

What I am trying to do here is modifying the style of a div depending on the scroll position you are on. In this case, when you scroll pass 20 it would change to EITHER one of these 3 conditions (100px in green background / 200px in yellow background / 300px in red background). It's doing the random style change in the demo, however it's constantly changing the style as you scroll. Is there a way to make it stay in the randomly selected style after you scroll pass that point?

4

1 回答 1

2

更改班级后使用on并禁用它来设置命名事件。off

var classes = ['a', 'b', 'c'];

$(window).on('scroll.changeClass', function() {
    if ($(this).scrollTop() > 20) {
        var cls = classes[Math.floor( Math.random() * classes.length )];
        $('#box').toggleClass(cls);
        $(this).off('.changeClass'); // remove the event as we are done here
    }
});

小提琴:http: //jsfiddle.net/ck5fa/2/

于 2013-11-02T01:01:47.870 回答