简体   繁体   中英

Smooth css change transitions

I've setup a jQuery function that changes the body background colour when a certain div comes into view, eg the body background colour is black, when #block-three (that contains black text), the body background colour changes to white, and changes back when this goes out of view. This works fine, it's just very sudden though, I'm looking for a much smoother transition between background colours, fading between colours as you scroll (if possible).
jsFiddle demo: http://jsfiddle.net/neal_fletcher/TB53d/

HTML:

<div id="block-one" class="block">
    <div class="inner-block">Test</div>
    <div class="inner-block"></div>
    <div class="inner-block"></div>
</div>
<div id="block-two" class="block">
    <div class="inner-block">Test</div>
</div>
<div id="block-three" class="block">
    <div class="inner-block">Test</div>
    <div class="inner-block"></div>
</div>
<div id="block-four" class="block">
    <div class="inner-block">Test</div>
    <div class="inner-block"></div>
    <div class="inner-block"></div>
</div>
<div id="block-five" class="block">
    <div class="inner-block">Test</div>
    <div class="inner-block"></div>
    <div class="inner-block"></div>
</div>

jQuery:

var blockHeight = [];
$(".block").each(function () {
    blockHeight.push($(this).height());
});

function hoverCurrentItem() {
    var sIndex = 0;
    var totalHeight = 0;
    var scrolled = $(window).scrollTop();
    for (var i in blockHeight) {
        totalHeight += blockHeight[i];
        if (totalHeight > scrolled) {
            break;
        } else {
            sIndex++;
        }
    }

    var $sItem = $(".block").eq(sIndex);
    if (!$sItem.hasClass("selected")) {
        $(".selected").removeClass("selected");
        $sItem.addClass("selected");
    }
    if ($("#block-three").hasClass("selected")) {
        $("body").css("background-color", "white");
    } else {
        $("body").css("background-color", "black");
    }
}
hoverCurrentItem();

$(window).scroll(function (e) {
    hoverCurrentItem()
});

Any suggestions would be greatly appreciated!

You could use transition with CSS:

body {
    background-color: black;
    transition:all 1s;
}

The Demo Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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