使用 jQuery 淡入背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12227901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:26:55  来源:igfitidea点击:

Fade in background image with jQuery

jqueryhtmlcssinternet-explorerfadein

提问by Mattias

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?

这是我第一次使用jQuery。我正在加载一个大的背景图像,当它被加载时,我会在三秒内褪色。此脚本适用于 Firefox 和 Chrome,但不适用于 IE(当然!)。是否有任何故障安全的方式使它在 IE 中神奇地工作,是否有一些更漂亮的编写方式?

<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);
  });
});

回答by SNAG

use

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

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

假设你从 style="opacity: 0;"

回答by daryl

HTML

HTML

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

CSS

CSS

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

Javascript

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);
  });
});

回答by krish

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);
  });
});