预加载用于更改背景图像的链接的图像

时间:2016-07-14 22:34:19

标签: jquery image

我正在尝试重新创建一个与此页面类似的页面:

http://www.farmleague.us/team/

使用此代码将鼠标悬停在我的链接上时,我成功使用jquery来更改背景图片:

<script>
// Since we're using these multiple times, assign them to variables
var $link = jQuery('#block-yui_3_17_2_2_1468449172411_5050');
var $image = jQuery('#collection-5786be4ed482e9c3a905d937');
// Get the original background image
var originalBackground = $image.css("background-image",       "url(https://static1.squarespace.com/static/57771b9e15d5dbc2f8fc084d/57771c55e3df28c63c9e687f/57771ca7440243196bc6801b/1467423990309/Gator.jpg?format=1500w)");
// jQuery hover supports TWO functions: first is "mouseover", second is "mouseout"
$link.hover(
// On mouseover, replace image
function() { 
    $image.css("background-image",  "url(https://static1.squarespace.com/static/57771b9e15d5dbc2f8fc084d/57771c55e3df2 8c63c9e687f/57771d441b631b48a1362df6/1467424076131/patagoniawater.jpg?format=750w)"); 
},
// On mouseout, put original image back
function() {
    $image.css("background-image",  "url(https://static1.squarespace.com/static/57771b9e15d5dbc2f8fc084d/57771c55e3df28c63c9e687f/57771ca7440243196bc6801b/1467423990309/Gator.jpg?format=1500w)", originalBackground);
}
); </script>   

但是,第一次将鼠标悬停在某个链接上时,会有一瞬间背景变为默认背景颜色,该颜色设置为透明。一旦我在链接上盘旋一次,背景图像来回变换,两者之间没有背景颜色,所以我猜测我是否加载了图像,我不会看到背景颜色。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

这是一个快速而又肮脏的东西,应该让你开始。

$(document).ready(function() {
  preloadImages();
})

function preloadImages() {
  var images = [
    'img/image1.jpg',
    'img/image2.jpg',
    'img/image3.jpg'
  ]

  images.each(function(){
    $('<img />').attr('src',this).appendTo('body').hide();      
  });
}

答案 1 :(得分:0)

我发现这是我之前在@cale_b

的上一个问题中回答的问题

stackoverflow.com/a/476681/870729

谢谢!

相关问题