How to make my CSS transition smoother / work in different browsers?

I am trying to make a page that changes the background image when a button is clicked. Code pen: http://codepen.io/meek/pen/EPLZpW

body {
  background: url('https://s3.eu-central-1.amazonaws.com/meek-img/1.jpg') no-repeat center center fixed;
  background-size: cover;
  -webkit-transition: background .5s ease-in-out;
  -moz-transition: background .5s ease-in-out;
  -o-transition: background .5s ease-in-out;
  transition: background .5s ease-in-out;
}

Two big problems with the way I'm doing it now:

  • It does not work in Mozilla Firefox.
  • The animation is not quite smooth. It instantly switches to a blank background, then the animation starts. Is there a way to prevent this, or is it inevitable due to load time? If so, are there other ways to implement this feature that would work around this? At first I thought about animation using jQuery, but I was told that this is not optimal.
+4
source share
2

background . , . . , , .

opacity (, div), . , , div, . , div .

, , . , , . , , . jQuery, vanilla JS.

function preload_img (src, callback) {
  var img = new Image();

  img.onload = function() {
    if( callback && typeof callback === 'function' ) {
      callback( img );
    }
  };
  
  img.src = src;
}

var imgs = [
  "https://s3.eu-central-1.amazonaws.com/meek-img/1.jpg",
  "https://s3.eu-central-1.amazonaws.com/meek-img/2.jpg",
  "https://s3.eu-central-1.amazonaws.com/meek-img/3.jpg", 
  "https://s3.eu-central-1.amazonaws.com/meek-img/4.jpg", 
  "https://s3.eu-central-1.amazonaws.com/meek-img/5.jpg", 
  "https://s3.eu-central-1.amazonaws.com/meek-img/6.jpg", 
  "https://s3.eu-central-1.amazonaws.com/meek-img/7.jpg", 
  "https://s3.eu-central-1.amazonaws.com/meek-img/8.jpg", 
  "https://s3.eu-central-1.amazonaws.com/meek-img/9.jpg" 
];

function change_bg() {
  var random_index = Math.floor(Math.random() * imgs.length);
  preload_img( imgs[random_index], function( img ) {
    $('<div>')
      .addClass('bg-image')
      .css('background-image', 'url(' + img.src + ')')
      .appendTo('body')
    ;
  } );
}

$( 'button' ).click( function() {
  change_bg();
} );

change_bg();
@keyframes fadein
{
  from { opacity: 0; }
  to { opacity: 1; }
}

.bg-image
{
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  animation: fadein 1s;
  background-size: cover;
}

.mimi
{
  z-index: 1;
  bottom: 0;
  height: 100px;
  left: 0;
  margin: auto;
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="mimi">
    <button class="btn btn-default btn-lg">click me</button>
  </div>
</body>
Hide result
+3

0, 1. .

, .

append(), 1.

+2

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


All Articles