javascript - 如何仅在单击时而不是之前加载图片

标签 javascript ajax ruby-on-rails-3 coffeescript overlay

我编写了一个漂亮的画廊,点击的图片覆盖在整个网页上。 问题是,所有图片和缩略图都是立即加载的,我只想加载大图片,当有人按下相应的缩略图时。 我没有 ajax 经验,尽管我尝试使用 :remote => true 做一些事情,但没有成功。有人可以帮忙吗?

<% for painting in @gallery.paintings %>
  <div class="painting">
  <%= image_tag painting.image_url(:thumb), :remote => true, :rel => "##{painting.id}" %>

    <div class="overlay" id="<%= painting.id %>" >
      <%= image_tag painting.image_url %>
    </div>
<% end %>

和我的 javascript coffe-script 文件

$(document).ready ->
  $("img[rel]").overlay();
  $(".close").click ->
    $("#dim").fadeOut()
    false
  $("div.painting img").click ->
    $("#dim").fadeIn()
    false
  $(".overlay").css "width", $(window).width()
  $("#dim").css "width", $(window).width()

$(window).bind "resize", ->
  $(".overlay").css "width", $(window).width()
  $("#dim").css "width", $(window).width()

编辑 2012/3/24:

我通过使用更改了 repo 协议(protocol):

  gem 'fancybox-rails', :git => 'https://github.com/sverigemeny/fancybox-rails'

开箱即用,看起来棒极了。

最佳答案

您无需了解 ajax 即可执行此操作,因为您只需在现有图像上设置源属性或创建图像元素即可。现在,如果您想从服务器检索 html 或 url 或其他内容,那么您将需要了解 ajax。让我们知道您是否正在这样做。

http://jsfiddle.net/mrtsherman/nzdpt/1/

<button id="a">Create element</button>
<button id="b">Swap src on img</button>
<img id="c" src="http://placehold.it/150x150/ff0000" />​
//create a new image element and append it to dom
$('#a').click(function() {
    var $img = $('<img />', {
             id: 'foobar ',
             src : 'http://placehold.it/150x150'
    });
    $('body').append($img);
});

//get an existing img element and change its source 
$('#b').click( function() {
    $('#c').prop('src', 'http://placehold.it/100x100');
});
​

关于javascript - 如何仅在单击时而不是之前加载图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9450461/

相关文章:

javascript - 使用 AJAX 为 AJAX 预加载图像

mysql - Rails 3 和 MySQL 的问题与 ActiveSupport 中的 JSON 依赖相关

javascript - Webapi编程暂停或休眠

javascript - 使用 JSTree 上下文菜单捕获新创建的节点

javascript - backbone.js 和处理来自 rails 的错误消息?

javascript - INVALID_STATE_ERR : DOM Exception 11

ruby-on-rails - 如何构建复杂的 Rails 系统

mysql - 使用 Mysql2 gem 的 Ruby SQL 插入

javascript - 在 Node 中安装自定义 SSL 证书 (UNABLE_TO_VERIFY_LEAF_SIGNATURE)

javascript - 评级明星列表的好关键 Prop