如何在Rails中使用link_to和mouseover制作image_tag超链接



我将*image_tag*图像放置在*link_to*元素中,并尝试进行鼠标悬停图像交换。除了鼠标悬停之外,一切都在工作,鼠标悬停没有抓取备用图像。更一般地说,我做超链接图像正确吗?抱歉,Rails新手。非常感谢!

<%= link_to (image_tag("#{product.prod_img}.jpg", alt: product.prod_name, class: 'img_prod_thumb', mouseover: "#{product.prod_img}_over.jpg")), "/products/#{product.id}" %>

两个指针:

  1. 除非有充分的理由,否则不要动态地将img扩展添加到代码中(尤其是在视图中)(?)
  2. 您可以使用简单的product作为路径,而不是硬编码的url

我会这么做:

>>> move product image name construction to the model, helper, or decorator
# model (for simplicity)
def prod_img_full
  "#{prod_img}.jpg"
end
def prod_img_over
  "#{prod_img}_over.jpg"
end
>>> update and clean up link_to
<%= link_to image_tag(product.prod_img_full, 
            alt: product.prod_name, 
            class: 'img_prod_thumb', 
            mouseover: product.prod_img_over), 
            product %>

您可以很容易地将image_tag移动到decorator,这将允许在您的视图中这样做:

<%= link_to product.hover_image, product %>

最新更新