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 badges3 Answers
Reset to default 6Are 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
版权声明:本文标题:javascript - Preload Mouseover Images in Rails - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744657277a2618041.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论