我有一个网页,使用一张大图作为背景。我希望使用jQuery在图像下载完成后再加载它(类似bing.com加载其背景图像的方式)。这在jQuery中是否可能?如果可以,您会推荐哪个插件?
我有一个网页,使用一张大图作为背景。我希望使用jQuery在图像下载完成后再加载它(类似bing.com加载其背景图像的方式)。这在jQuery中是否可能?如果可以,您会推荐哪个插件?
您可以先加载图像,然后在其完成加载后将其设置为背景图像。这样,浏览器将(希望)从缓存中加载背景图像,而不是重新下载它。由于您要求它作为插件:
$.fn.smartBackgroundImage = function(url){
var t = this;
//create an img so the browser will download the image:
$('<img />')
.attr('src', url)
.load(function(){ //attach onload to set background-image
t.each(function(){
$(this).css('backgroundImage', 'url('+url+')' );
});
});
return this;
}
使用方式如下:
$('body').smartBackgroundImage('http://example.com/image.png');
$('<img />').attr('src', url).load(function(){ $('#yourContainerDiv').css('backgroundImage', 'url('images/yourImage.png')' ); $('#yourContainerDiv').fadeIn('slow'); }); });
对于格式不当,敬请谅解。请将其粘贴到您的编辑器中以阅读。评论中不允许使用代码块。 - Jeremy Penrod这篇文章可能会对你有所帮助。以下内容来自该文章:
HTML
<div id="loader" class="loading"></div>
CSS
DIV#loader {
border: 1px solid #ccc;
width: 500px;
height: 500px;
}
/**
* While we're having the loading class set.
* Removig it, will remove the loading message
*/
DIV#loader.loading {
background: url(images/spinner.gif) no-repeat center center;
}
Javascript
// when the DOM is ready
$(function () {
var img = new Image();
// wrap our new image in jQuery, then:
$(img)
// once the image has loaded, execute this code
.load(function () {
// set the image hidden by default
$(this).hide();
// with the holding div #loader, apply:
$('#loader')
// remove the loading class (so no background spinner),
.removeClass('loading')
// then insert our image
.append(this);
// fade our image in to create a nice effect
$(this).fadeIn();
})
// if there was an error loading the image, react accordingly
.error(function () {
// notify the user that the image could not be loaded
})
// *finally*, set the src attribute of the new image to our image
.attr('src', 'images/headshot.jpg');
});
你不能使用CSS背景图片,因为我所知道的,无法将事件附加到图像的加载上。
所以我会尝试一下,但还没有测试过:
HTML:
<body>
<div class="bgimage"><img src="/bgimage.jpg" ></div>
<div>
... content ...
</div>
</body>
CSS:
.bgimage { position: absolute: }
Javascript:
$(function() {
$(".bgimage")
.css("opacity",0);
.load(function() { $(this).fadeIn(); });
});
jQuery.preloadImages = function() {
for (var i = 0; i < arguments.length; i++) {
jQuery("<img>").attr("src", arguments[i]);
$('.box1').attr('preloadURL', arguments[0]);
}
}
$.preloadImages("sky.jpg");
$(document).ready(function() {
if ($('.box1').attr('preloadURL') == 'sky.jpg') {
$('.box1').css({ 'background-image': 'url(sky.jpg)' },$('.box1').fadeIn(1000));
}
});
标记语言:
<div class="Content">
<label>Search Bing</label>
<input type="text" />
<input type="button" value="search" />
</div>
<div class="box1"></div>
样式表:
.box1 {background-repeat:no-repeat; width:800px; height:600px; display:none; position:relative;}
.Content { position:absolute; left:20px; top:20px; z-index:100;}
.Content label { color:White;}