admin管理员组

文章数量:1394217

I currently have a rollover button implemented in rails as follows:

<%= image_tag("header/home_but.gif", :mouseover => "header/home_over.gif") %>

How can I preload/cache the mouseover image (home_over.gif) so there is no delay when the user moves their mouse over the image? Thanx.

I currently have a rollover button implemented in rails as follows:

<%= image_tag("header/home_but.gif", :mouseover => "header/home_over.gif") %>

How can I preload/cache the mouseover image (home_over.gif) so there is no delay when the user moves their mouse over the image? Thanx.

Share Improve this question asked Nov 10, 2009 at 21:45 Chris CChris C 3738 silver badges18 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Are you sure you don't want a CSS Sprite here? Basically you put your image states into one image (Photoshop), set the image as the background of an anchor element, then adjust the visible area with CSS for the background property and the :hover and :visited states. Only one image has to download this way.

My environment uses jQuery, so I wanted the solution to use jQuery as well.

I found another question about preloading images with jQuery, and it's top answer had the jQuery prewritten for me. I adapted my code as follows into ERB:

<% alternate_images = [] %>
<% @resources.each do |resource| %>
  <%= image_tag(resource.primary_image.url, :mouseover => resource.alternate_image.url) %>
  <% alternate_images << resource.alternate_image.url %>
<% end %>
<script type="text/javascript">
$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}
$([<% alternate_images.each do |image| %>
     "<%= image %>",
   <% end %>]).preload();
</script>

I'm not a rails programmer, but my understanding is that Rails uses Prototype by default. Assuming that, you could include this JavaScript:

Prototype.preloadImages = function(){
    for(var i=0, images=[]; src=arguments[i]; i++){
        images.push(new Image());
        images.last().src = src;
    }
};

Then add this code wherever your onload code runs. Maybe something like this:

Event.observe(window, 'load', function(){
    Prototype.preloadImages('header/home_over.gif','another/image/to/preload.gif');
});

You'll have to assure that whatever magic image_tag() does is done to the image paths to assure that the correct image is preloaded.

本文标签: javascriptPreload Mouseover Images in RailsStack Overflow