0
私はRails 4を使用して、1つの大きな画像と6つのサムネイルを持つページを持っています。 ユーザーがサムネイルの1つをクリックすると、大きな画像がクリックされたサムネイルの1つに変わります。私のアプリ/ビュー/製品/ show.html.erbでrails:image urlが動的なときにクリックしたときに画像を変更する
:
<div class="product-teaser-column">
<%= image_tag product_image_url(@product, type: :three_quarter, color: colors.first), itemprop: "image", class: 'teaser' %>
</div>
<div class="product-thumbnail-column">
<ul class="product-thumbnails" class "thumbnails inline">
<% type_map.except(:thumb, :reversiblefront).each_with_index do |type, index| %>
<li class='thumbnail'>
<%= image_tag product_image_url(@product, type: type, color: colors.first), itemprop: "image", class: 'thumbnail' %>
</li>
<% end %>
</ul>
</div>
私はアプリ/資産/画像の画像ファイルを持っていたとjQueryを使って、この機能を実装しました。アプリ/資産/ JavaScriptの/ application.jsで :
// change teaserimage on thumbnail-click
$(function() {
var images = [
"/assets/Nile_1_16_0119.jpg", "/assets/Nile_1_16_0095.jpg",
"/assets/Nile_1_16_0131.jpg", "/assets/Nile_1_16_0144.jpg",
"/assets/thumb_midnight.jpg", "/assets/back_midnight.jpg"
];
$(".thumbnail").click(function() {
var index = $(this).parent().index();
$('img.teaser').attr('src', images[index]);
$(this).parent().siblings().removeClass('active');
$(this).parent().addClass('active');
});
});
がどのように画像のURLが動的であるときことを達成することができますか?
アプリ/ヘルパー/ products_helpers.rb:
module ProductsHelper
def product_image_url(product, type:, color:)
source = URI.escape "#{product_image_base_url}/#{collection_folder(product)}/"\
"#{product_number(product)}_#{product_type(type)}"\
"_#{format_color_name(color.name)}.jpg"
image_exist?(source, product) ? source : false
end
def product_image_base_url
ENV['PRODUCT_IMAGE_BASE_URL']
end
def product_number(product)
product.number.strip.upcase
end
def product_type(type)
type_map.fetch(type)
end
def type_map
@type_map ||= {
full: "01",
three_quarter: "02",
medium: "03",
close_up: "04",
front: :front,
back: :back,
thumb: :thumb,
reversiblefront: :reversiblefront
}
end
end
ねえ、サムネイルクリックイベントから画像srcを取得し、jqueryのメイン画像srcを置き換えることができます。 –
ありがとうHardik、そうだね、思ったよりずっと簡単だよ! – StandardNerd