Fade in background image with jQuery

女生的网名这么多〃 提交于 2019-12-18 09:54:27

问题


This is the first time I am using jQuery. I am loading a large background image and when it is loaded I am fading it in over three seconds. This script works on Firefox and Chrome but not in IE (of course!). Is there any fail safe way of making it magically work in IE and is there some prettier way of writing it?

<div class="bgImage" />

$(document).ready(function () {
  // add bg image and fade
  var _image = new Image();
  _image.id = 'newImageId';
  _image.src = "./css/background.jpg";

  $(_image).load(function () {
    $('div.bgImage').css('background-image', 'url(./css/background.jpg)');
    $('div.bgImage').fadeTo(3000, 1);
  });
});

回答1:


use

 $('div.bgImage').animate({ opacity: 1 }, { duration: 3000 });

assuming you are starting of with style="opacity: 0;"




回答2:


HTML

<body>
  <div class="bgImage"></div>
  ...
</body>

CSS

.bgImage {
  position: fixed;
  top: 0; left: 0;
  right: 0; bottom: 0;
  z-index: 1;
  display: none;
}

Javascript

$(function() {
  var src = '../css/background.jpg';
  var ele = $('.bgImage');
  var img = $('<img>', {
    src: src
  }).hide().appendTo(ele).load(function() {
    $(this).remove();
    ele.css('background-image', 'url('+src+')').fadeIn(3000);
  });
});



回答3:


for this you dont need to write that many lines of code this simple code will work for u...

$(document).load(function () {
  $('div.bgImage').css('background-image', 'url(./css/background.jpg)');

  $(document).ready(function () {
    $('div.bgImage').fadeIn(3000);
  });
});


来源:https://stackoverflow.com/questions/12227901/fade-in-background-image-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!