Replenish the div gradually when moving to another element

I want to set up a menu that gradually changes color depending on its position on various div sites. Let's start with the blue box on the white div, and when you come to the second black div, gradually moving the box to white.

But if the box stays between the two divs, it takes 50/50 respectively the opposite color for each div that is full.

I have no problem changing the state according to the colors, but I can’t make a smooth transition of color, not suddenly.

Here is a demo:

$(window).scroll(function () {
    console.log($(".menu").offset().top);
    console.log($(".blue").offset().top - 30);

    if ($(".menu").offset().top < ($(".blue").offset().top - 100)) {
        $(".menu").css("top", "30px");
        $(".menu").css("background-color", "#34495e");
    } else {
        $(".menu").css("background-color", "#ecf0f1");
    }
});
body {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  padding: 0;
}

.white {
  width: 100vw;
  height: 800px;
  background-color: #ecf0f1;
}

.blue {
  width: 100vw;
  height: 800px;
  background-color: #34495e;
}

.menu {
  position: fixed;
  left: 100px;
  top: 20px;
  width: 100px;
  height: 100px;
  background-color: #34495e;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="white"></div>
<div class="blue"></div>
<div class="menu"></div>
Run codeHide result

Thanks in advance for your answers and advice.

I am adding a picture for reference: http://img11.hostingpics.net/pics/383878example.jpg

+4
source share
2

div?

$(window).scroll(function () {
    var menu = $(".menu");
    var blue = $(".blue");
    var gradient;
    var line;
    console.log(menu.offset().top);
    console.log(blue.offset().top - 30);

    if (menu.offset().top < (blue.offset().top) - 100) {
        menu.css("top", "30px");
        menu.css("background", "#34495e");
    } else if (menu.offset().top < blue.offset().top) {
        line = blue.offset().top - menu.offset().top;
        gradient = "linear-gradient(to bottom, #34495e " + line + "px,#ecf0f1 " + line + "px)";
        menu.css("background", gradient);
    } else {
        menu.css("background", "#ecf0f1");
    }
});

http://jsfiddle.net/49xhszhx/

+5

: , , .
: JSFiddle

CSS

transition: background-color 1s;

JS:

$(window).scroll(function () {
console.log($(".menu").offset().top);
console.log($(".blue").offset().top - 30);

if ($(".menu").offset().top < ($(".blue").offset().top - 100)) {
    $(".menu").css("top", "30px");
    $(".menu").css("background-color", "#34495e");
} else if ($(".menu").offset().top < ($(".blue").offset().top - 50)){
    $(".menu").css("background-color", "#6C7E8F");
    }
else{
    $(".menu").css("background-color", "#ecf0f1");
}

});

+1

Source: https://habr.com/ru/post/1599590/


All Articles