Css затемнение фона при прокрутке

Как реализовать смену фона блока при прокрутке страницы?

Есть див, который движется медленнее относительно других элементов страницы при прокрутке. У этого дива фон задан изображением. Как можно реализовать плавную смену фона блока (фоновых изображений всего 4) при прокрутке страницы? Например, как здесь (блок «Самый мощный iMac в истории»).

поставить 4 див блока с разным фоном абсолютом друг в друга и менять прозрачность при прокрутке и показывать тот блок который нужен

Див движется, фон или картинка в нем меняются. В чем проблема-то? Конкретно я сходил за вас и скопировал действующее вещество.

$(window).scroll(function() <
// 200px от верха
if ($(window).scrollTop() > ‘200’) <
$(‘#div’).css(<"background":"url(http://www.fonstola.ru/pic/201111/1600x900/fonstola.ru-55699.jpg);">);
>
// 400px от верха
if ($(window).scrollTop() > ‘400’) <
$(‘#div’).css(<"background":"url(http://www.zastavki.com/pictures/originals/2012/Backgrounds_Circles_colors_035456_.jpg);">);
>
// низ активного окна.
if ($(window).scrollTop() == $(document).height() — $(window).height()) <
alert($(window).scrollTop());
$(‘#div’).css(<"background":"url(http://www.fonstola.ru/pic/201111/1366x768/fonstola.ru-55713.jpg);">);
>
>);

kostyanet, а как «транслейт делает смещение»? Это через яваскрипт прописывается, чтобы значения обновлялись?

На примере отслеживается позиция при прокрутке и в определенном моменте у блока меняется position с absolute на fixed. И применяется transform: translate3d для каждого движения колеса мыши. Если не усложнять, то лучше как в примере выше через Jquery учитывать положение при прокрутке, а в CSS элемента добавить transition с нужными значениями для плавности смены фона.

Источник

Затемнение фона при прокрутке вниз

Вот встретил на сайте интересное оформление ( http://www.master-live.ru ), при прокрутки страницы вниз, фон становится более темнее. Как это сделать? Как-то через градиент, если да, то как?

Затемнение фона при наведении на ссылку
Всем здравствуйте! Смотрите, есть ссылка: <a href="http://site.ru">site</a> как.

Сделать затемнение заднего фона при отображении фото
Как мне сделать затемнение заднего фона при отображении фото помогите пожалуйста я в этом деле.

При прокрутке на телефоне блок чуть движется вниз
обычный блок position:fixed; top:0%; left:0%; width:100%; height:100%; если пролестнуть.

Читайте также:  Использование всплывающих окон javascript

Как создаются эффекты движения при прокрутке страницы вниз?
Как создаются эффекты движения при прокрутке страницы вниз? Здесь пример.

Лучший ответ

Сообщение было отмечено Паскалька как решение

Решение

ЦитатаСообщение от Паскалька Посмотреть сообщение

1 2 3 4 5 6 7 8 9 10 11 12
#content { height: 100%; background: #f0f9ff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f0f9ff), color-stop(100%,#6996d3)); background: -webkit-linear-gradient(top, #f0f9ff 0%,#6996d3 100%); background: -moz-linear-gradient(top, #f0f9ff 0%, #6996d3 100%); background: -ms-linear-gradient(top, #f0f9ff 0%,#6996d3 100%); background: -o-linear-gradient(top, #f0f9ff 0%,#6996d3 100%); background: linear-gradient(to bottom, #f0f9ff 0%,#6996d3 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f0f9ff', endColorstr='#6996d3',GradientType=0 ); }

Есть минус( Он не рассчитан на длинные страницы. То есть идет повторение, а надо чтобы плавно всю страницу, независимо от размера.

Вот посмотри что получилось http://wpcofe.ru/

ЦитатаСообщение от Паскалька Посмотреть сообщение

Лучший ответ

Сообщение было отмечено Taatshi как решение

Решение

Хитрость лучшие качество программиста, но оно в данный момент не помогло(
Попробую найти решение, найду, выложу сюды.

Добавлено через 1 минуту
А, все, получилось.

Добавлено через 2 минуты
А нет, не до конца. Получается еслибольшой размер установить, то просто страница удленяется, но градиент работает, а если 100% ставить, то не работает нормально

Добавлено через 1 минуту
Все догадался. Добавил вот это

height:auto !important; height:100%;
1 2 3 4 5 6 7 8 9 10 11 12
html,body { height:auto !important; height:100%; background: #f0f9ff; background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f0f9ff), color-stop(100%,#6996d3)); background: -webkit-linear-gradient(top, #f0f9ff 0%,#6996d3 100%); background: -moz-linear-gradient(top, #f0f9ff 0%, #6996d3 100%); background: -ms-linear-gradient(top, #f0f9ff 0%,#6996d3 100%); background: -o-linear-gradient(top, #f0f9ff 0%,#6996d3 100%); background: linear-gradient(to bottom, #f0f9ff 0%,#6996d3 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f0f9ff', endColorstr='#6996d3',GradientType=0 ); }

При увеличение размера фона он съезжает вниз
Здравствуйте! Как только меняю значение height у главного фона он съезжает. Изначально 1522.

Читайте также:  Отступы между блоками css grid

Затемнение фона
Здравствуйте. Я только начал изучать верстку сайтов и вот столкнулся с такой проблемой. Нужно.

Затемнение нижней части фона сайта
Думаю такая дема уже была, и не раз.. Требуется затемнение нижней части сайта. Пациент ТЫЦ (Не.

Источник

How to smoothly transition and change background color while scrolling using CSS?

I wanted to smoothly transition and change background color while scrolling, preferably using just CSS, and came across the following as a good example: https://minimill.co/ How can I achieve the smooth transition in changing the background color? And also when a button is clicked on the navigation bar, navigate to that particular section of the page? I attempted to check the source code but wasn’t any help. The whole source code is in 1 line. Thank you and will be sure to vote up and accept answer.

A good example on how to change the background color while scrolling is on this link: https://codepen.io/Funsella/pen/yLfAG, or the second version of this in this link http://codepen.io/Funsella/pen/dpRPYZ

@Thanasis Wow thank you so much but it is using a framework/plugin? And would there be an alternative to achieving it without using CSS?

The first link uses the scrollie jQuery Plugin. The second link uses the in-view plugin. And they both use jQuery. In general you can see which plugins are used by clicking the little settings button left from the title JS.

2 Answers 2

WITHOUT EXTRA PLUGINS

If you want to use only JavaScript then you can go about this solution.

In the code below I have 3 divs and each one has the attribute data-color which contains the color that we want to have on the background when the user is over that div. I made it so the color changes not just when the div is on top of the page but when we are after the 2/3 of the previus div.

Читайте также:  Read write memory python

Also included below are the jumps that you wanted. From the first div there is a link that sends you to the second div etc. You can modify them to fit your navigation bar. In order to understand jumps better you can look here.

var test = document.getElementById("test"); document.onscroll = function() < scrollTop = document.documentElement.scrollTop; test.innerHTML = scrollTop; allDivs = document.getElementsByTagName('div'); for( i=0; i< allDivs.length; i++ ) < curDiv = allDivs[i]; // The code below makes the background color change when the // scroll top passes the 2/3 of the previous div. heightBefore = 0; if (i >0) < heightBefore = allDivs[i-1].offsetHeight / 3; >if (scrollTop > curDiv.offsetTop - heightBefore) < color = curDiv.getAttribute("data-color"); document.body.style.background = color; >> >;

Title goes Here

Green area

Go To Red area

Red area

Go To Blue area

Blue area

Return To Green area

In order to make it work on different browsers too, you must add these lines in the CSS:

-webkit-transition: background 1.5s; -moz-transition: background 1.5s; -ms-transition: background 1.5s; -o-transition: background 1.5s; transition: background 1.5s; 

and then change the scrollTop initialization in javascript from this:

scrollTop = document.documentElement.scrollTop; 
scrollTop = window.pageYOffset; 

You can test it in this updated JSFiddle.

WITH EXTRA PLUGINS

smoothly transition and change background color while scrolling

as I wrote in the comment these sources are very helpful:

The examples in these links use javascript, jquery and other plugins, which I think are neccesary.

when a button is clicked on the navigation bar, navigate to that particular section of the page

this link explains it very well:

Below there is a small example of what you want, that was created by using and combining content from the links above:

  

Title

Go To Green.

Green area

Go To Red.

Red area

Page over. Hope that was helpful :)

Источник

Оцените статью