Плавная смена фона html

How can I smoothly transition CSS background images?

@dandavis It doesn’t transition opacity, does it. Hold on. If it was that simple, these guys wouldn’t be suggesting hacks..

@jt0dd: i don’t know the details, i’m surprised it works at all! (i did test in chrome before commenting). it was new to me. it would be seem to be ideal for going from low-rez to high-rez, or from a (semi?) transparent png to a regular background image. when i went from a small image to a big one with 3000ms duration, the repeating image slowly grew. might need other props like background-size to get looking just right, but it looked promising enough to comment.

3 Answers 3

As noted in the comments by @dandavis, there’s actually a CSS transition property : background-image.

The solution, utilizing the CSS background transition property:

  1. create two background images of the same size: one transparent & one that’s intended. (If you don’t make them the same size, you’ll get this effect!);
  2. use transition: background-image 1s to cause the transition effect
  3. use Javascript to preload the image and reset the background image when it’s ready. CSS will take care of the rest.

Notable Limitations

  • This does not allow for background-size manipulation ( this results in a very weird effect).
  • The images, as mentioned, must be the same size.
var image = new Image(); image.onload = function () < $(".element").css("background-image", "url('" + image.src + "')"); >image.src = "https://c1.staticflickr.com/3/2439/3728897793_ff1c78c5d9.jpg"; //image to be transitioned to

@ZachSaucier In the comments, dandavis prompts for another user to test his solution rather than posting an answer. So I went ahead and did the testing, posting my results as an answer.

I think I have a solution! (sorry, just very exited I got this working:)

//library (minified) this.BgImgFader=function()if(str.lastIndexOf(',')==str.length-1)if(str.indexOf(',')==-1)elsefor(var i=0;ireturn selectors;>function getStyleSheet(style)else>>>function addStyleRule(sheet,selector,declarations)else');>>this.prepare=function(style,selectors)>;this.fade=function(style,selectors,global,opacity,endOpacity,delta);function fadeOpacity(selectors,global,opacity,endOpacity,delta,rules)else if(styleRules[j].selectorText.toLowerCase()==selectors[i].toLowerCase()+'::after')>>>for(var i=0;iif(opacity,0);>elserules.length=0;>>>; //instantiate BgImgFader in global domain var BgImgFader = new BgImgFader(); window.onload = function()< //prepare specified elements BgImgFader.prepare(0, '.exampleClass'); //style, selectors //fade specified elements BgImgFader.fade(0, '.exampleClass', true, 0, 0.5, 0.002); //style, selectors, global, startOpacity, endOpacity, delta >;
#exampleId < width: 300px; height: 200px; margin: 10px 0px 0px 10px; background-color: #AAAAAA; >#exampleId .exampleClass < width: 200px; height: 130px; padding: 5px; >#exampleId .exampleClass::after 
 
Some other text to illustrate how this can be implemented.
I assume you want transparent background images because you have text in the element that you do want to show from the start?

I basically ended up building a tiny library. Pure JavaScript, no jQuery required.

All you have to do is add these three BgImgFader lines in JS:

//instantiate BgImgFader in global domain var BgImgFader = new BgImgFader(); window.onload = function()< //prepare specified elements BgImgFader.prepare(0, '.exampleClass'); //stylesheet, selectors //fade specified elements BgImgFader.fade(0, '.exampleClass', true, 0, 0.5, 0.002); //stylesheet, selectors, global, startOpacity, endOpacity, delta >; 

And add the following to all your background-image-elements in CSS:

So for every element with a background-image, you have to add the #example::after < rule and place your background-image in there. (You do NOT have to do this in HTML, only in CSS.)

I’ve added the library’s source code as a code snippet below. Comments are in the code.
You can either paste the code at the top of your own script, or put the code in a file and in your HTML, link to that file like you would to any other library (before your own code):

/** * BgImgFader - Library: * This library makes it possible to fade the background-image of an element. * The image can be faded in or out. * * Compatibility: * - IE9 and higher should be fine, lower could give trouble. * - Older versions of FF/Chrome will probably give some problems too, but I think we can safely assume * that those who chose either one of these browsers, did so because they choose NOT to live in the past.. * - Opera and others. I have absolutely no idea. * * ################################################################################# * INSTRUCTIONS--------------------------------------------------------------------- * 1. In CSS: * a. For every element with a background-image, create an '::after' rule, and put the image in there: * (You don't have to create these '::after'-elements in the HTML) * * #element * #element::after * * The following declarations will be added by the BgImgFader, keep that in mind: * #element * #element::after * * (The important one is 'position:relative;', the ones on the '::after'-element have no consequences) * * --------------------------------------------------------------------------------- * 2. In JavaScript: * a. Instantiate the BgImgFader in the global domain: var BgImgFader = new BgImgFader(); * * * b. Prepare the elements with a background-image: BgImgFader.prepare(0, 'elements'); //style, selectors * * - style: Reference to the style sheet with the rules for the specified elements. * This can be either an INTEGER for internal style sheets (0), * or a STRING of a filename for external style sheets ('style.css'). * - selectors: STRING reference to the selectors in the style rules. * This works the same as in the CSS, below a few examples. * Individual tags: ('div') ('#id') ('.class') * Multiple tags: ('div.class') ('#id .class') ('.class.subclass') * Multiple selectors: ('div, #id, div.class, #id .class, .class.subclass') * * * c. Initiate the fade: BgImgFader.fade('style.css', 'elements', true, 0, 0.5, 0.005); //style, selectors, global, startOpacity, endOpacity, delta * * - style: See 2b for the details. * - selectors: See 2b for the details. * - global: BOOLEAN that deternimes whether only complete matches for the selectors are allowed, * or partial matches as well, increasing the range of the BgImgFader. * TRUE allowes partial matches: feed the BgImgFader '.class' and it will also try to fade 'div .class'. * FALSE allowes only complete matches. * - startOpacity: FLOAT that indicates the start opacity (0.0 - 1.0). * - endOpacity: FLOAT that indicates the end opacity (0.0 - 1.0). * - delta: FLOAT that indicates the delta of every fade-iteration (1.0 - 0.00000000. 1). * The effective range is approximately (0.1 - 0.0001). * A smaller delta means a slower fade. * A positive delta in combination with startend fades the image out. * * ################################################################################# */ this.BgImgFader = function() < var styleRules; //GET/SET-FUNCTIONS================================================================= //GET SELECTORS--------------------------------------------------------------------- function getArray(str) < /* This function is invoked by this.prepare() and this.fade(). * This function converts the specified string of selectors to an array, and returns that. */ //strip trailing comma's if (str.indexOf(',')==0) //strip first comma if (str.lastIndexOf(',')==str.length-1) //strip last comma //store selectors in array if (str.indexOf(',')==-1) else //trim trailing spaces for (var i=0; i return selectors; > //GET STYLE SHEET------------------------------------------------------------------- function getStyleSheet(style) < /* This function is invoked by this.prepare() and this.fade(). * This function returns a reference to the specified style sheet, * based on either a number or a filename of the sheet. * A number is for internal sheets, where the number stands * for its location in the HTML (e.g. the first ' '). * A filename is for external sheets (e.g. 'style.css'). * See the instructions in the header of this file for details. */ if (typeof style === 'number') < return document.styleSheets[style]; >else < //find style sheet for (var i=0; i> > > //SET STYLE RULE-------------------------------------------------------------------- function addStyleRule(sheet, selector, declarations) < /* This function is invoked by this.prepare(). * This function dynamically adds the specified rule to the specified style sheet. */ if (sheet.addRule) //IE. else ');> //NON-IE. > //PREPARE=========================================================================== this.prepare = function(style, selectors) < /* This function is invoked by an external function, outside of the library. * This function is an interface for external scripts to access this library. * The function prepares the elements specified by the selectors, by adding certain style rules * to them that are necessary for this library to successfully manipulate the background-image. */ var selectors = getArray(selectors); var styleSheet = getStyleSheet(style); for (var i=0; i>; //FADE BACKGROUND IMAGE============================================================= //INIT------------------------------------------------------------------------------ this.fade = function(style, selectors, global, opacity, endOpacity, delta) < /* This function is invoked by an external function, outside of the library. * This function is an interface for external scripts to access this library. * The function initiates the fading process. It first stores the appropriate * set of style rules into the style rules variable, and then invokes * fadeOpacity() to start the fading. */ var selectors = getArray(selectors); var styleSheet = getStyleSheet(style); styleRules = styleSheet.rules ? styleSheet.rules : styleSheet.cssRules; //IE uses 'rules', NON-IE use 'cssRules' fadeOpacity(selectors,global,opacity,endOpacity,delta,[]); >; //FADE------------------------------------------------------------------------------ function fadeOpacity(selectors, global, opacity, endOpacity, delta, rules) < /* This function is invoked by fade(). * This function fades the background-image of the specified elements, by * adding the delta to the current opacity, and then setting the opacity * of all specified elements to that new value. */ opacity += delta; if (rules.length == 0) < //find the css-rules that match the specified selector(s) for (var i=0; ielse if (styleRules[j].selectorText.toLowerCase() == selectors[i].toLowerCase()+'::after') < rules.push(styleRules[j]); break; >> > > //set the opacity of the background-image for every matched rule for (var i=0; i //check if the end-opacity is reached if (opacity < endOpacity) < setTimeout(function(),0); //invoke itself again > else < //manually set the opacity to the end-opacity (otherwise it'll be off by a fraction) for (var i=0; irules.length = 0; > > >;
source code of library, not a working code snippet!

Interesting fact: This does not work on jsfiddle.net, because their own style sheets get mixed in with the one from the fiddle, making it impossible to determine in which sheet (based on number) the required CSS-rules reside.

Источник

Плавное изменение background

Анимацию можно легко сделать через CSS свойство transition например для кнопок, меню и т.д. Подробнее на htmlbook.ru.

Transition background

Например, изображение меняются при наведении на него курсора мыши ( :hover ).

Transition background-size

Также transition можно применить к размеру изображения ( background-size ).

Как дополнение, можно добаввить смену background-image :

Комментарии

Другие публикации

Не стандартный СSS градиент

Полупрозрачный градиент поверх картинки

Такой эффект можно сделать с помощью :before у родительского элемента. Поверх изображения помещается абсолютный блок с.

Contenteditable – текстовый редактор

Если добавить атрибут contenteditable к элементу, его содержимое становится доступно для редактирования пользователю, а.

Генерация QR-кода в PHP

Вопрос генерации QR-кодов в PHP достаточно освещён, есть много библиотек, одной из них является «PHP QR Code» – быстрый и легкий класс, рассмотрим его применение совместно с графической библиотекой.

Текст с градиентом

Градиент в цвет шрифта можно добавить с помощью CSS свойства background-clip: text, которое окрашивает текст в цвет или изображение указанного в background-image.

Как сделать несколько фонов в background

В CSS3 появилась возможность указать в свойстве background несколько изображений (Multiple Backgrounds), при этом они.

Источник

Плавные трансформации на чистом CSS. Свойство transition

CSS-свойство transition служит для создания плавных переходов между двумя состояниями элемента. Оно помогает избежать резких и нежелательных изменений, делая анимацию более естественной и приятной для глаз.

Свойство в общем виде записывается так:

transition: property duration timing-function delay; 
  • property — определяет CSS-свойство, для которого будет применяться переход. Можно указать несколько свойств, разделив их запятой. Если указать all , переходы будут применяться ко всем свойствам элемента.
  • duration — определяет длительность перехода. Задаётся в секундах ( s ) или миллисекундах ( ms ).
  • timing-function — определяет скорость перехода в разные моменты времени. Наиболее часто используются следующие функции: linear , ease , ease-in , ease-out , ease-in-out .
  • delay — время задержки перед началом перехода. Задаётся в секундах ( s ) или миллисекундах ( ms ).

Примеры использования

В данном примере применяем плавный переход цвета фона ( background-color ) для элемента p при наведении курсора. Фон плавно изменится за секунду.

👉 Если вы не понимаете, что написано в этом примере кода и откуда там p , прочитайте статью про селекторы.

В этом примере применяем переход для двух свойств ( width и height ) одновременно. При наведении курсора размеры элемента p плавно увеличиваются.

Анимировать изменение цвета текста при наведении на ссылку.

Изменение размера шрифта при наведении на текст:

Нюансы

☹️ Не все свойства возможно анимировать. Для корректной работы перехода изменяемое свойство должно быть анимируемым. Например:

  • Цветовые свойства: color , background-color , border-color и другие.
  • Размеры и отступы: width , height , padding , margin , top , right , bottom , left и другие.
  • Свойства трансформации: transform (включая rotate , scale , translate , skew и другие).
  • Некоторые свойства текста: font-size , letter-spacing , word-spacing , line-height .
  • Свойство прозрачности: opacity .
  • Свойства границы: border-width , border-radius .
  • Свойство позиционирования: position .

❌ Не все CSS-свойства могут быть анимированы. Например, свойства display , content , visibility и некоторые другие не поддерживают анимацию.

Переходы не работают при изменении свойств с помощью JavaScript. В этом случае лучше использовать CSS-анимации или JavaScript-анимации.

Если вам нужна более сложная анимация или нужно анимировать изменение свойств, которые не поддерживают переходы, вы можете использовать CSS-анимации с помощью свойств @keyframes и animation .

Поддержка браузерами

Свойство transition хорошо поддерживается всеми современными браузерами. Для детальной информации рекомендуется обратиться к сайту caniuse.

Материалы по теме

  • Тренажёры по CSS-анимациям от HTML Academy.
  • : hover, : focus, : active — как работают состояния элементов.
  • Функции плавности — подборка функций плавности от Андрея Ситника и Ивана Соловьева.

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Источник

Читайте также:  Php engine on windows
Оцените статью