【问题标题】:button with an image?带有图像的按钮?
【发布时间】:2011-06-22 11:31:05
【问题描述】:

我正在尝试创建一个带有图像的按钮。所以基本上,我需要下面代码的 button_to 版本:|

<%= link_to image_tag(product.image_url, :class => "img"), line_items_path(:product_id => product) %>    

【问题讨论】:

  • 请说明问题所在并提供有关您遇到的错误的信息

标签: ruby-on-rails


【解决方案1】:

这是一篇相当老的帖子,但供将来参考:从 Rails 3.2.1 开始,您可以使用 button_tag 而不是 button_to,因为第一个本机允许图像:

创建一个按钮元素,定义提交按钮、重置按钮或可在 JavaScript 中使用的通用按钮,例如。您可以将按钮标签用作常规提交标签,但旧版浏览器不支持它。但是,按钮标签允许更丰富的标签,例如图像和强调,所以这个助手也将接受一个块。

至于你的例子:

<%= button_tag image_tag(product.image_url), line_items_path(:product_id => product), class: 'img' %>

我没有测试代码,但它应该可以工作。您可能需要使用url: 声明网址

【讨论】:

    【解决方案2】:

    这是我的解决方案:

    使用按钮助手(可以使用 button_to 助手方法):

    <%= f.submit 'Save', :class => "button_with_image_save" %>
    

    CSS:

    .button_with_image_save {
        background: url(../images/icons/page_save.png) #f2efa8 no-repeat 10px 6px;
        text-indent:30px;
        display:block;
        cursor: pointer;
    }
    

    【讨论】:

      【解决方案3】:

      简短的回答是您需要创建一个辅助方法,这很简单:

      这是一个类似的 SO 发布解释它:Is there a way with rails form helper to produce a button tag for submit

      祝你好运

      【讨论】:

        【解决方案4】:

        图片提交按钮:

        <%= image_submit_tag("team/team1.png", class: 'image-responsive') %>
        

        图片链接:

        <%= link_to(image_tag("team/team1.png", class: 'image-responsive'), root_path,  :method => :get) %>
        

        【讨论】:

          【解决方案5】:

          添加图片是文件夹app/assets/image

          在视图中

          <%= image_submit_tag('nameimage.png') %>
          

          缺点是不能随大小改变大小,但必须有你想出现的大小的图片

          【讨论】:

            【解决方案6】:

            您可以创建一个 helper 作为 button_to 链接 -

            <%= button_to product.image_url, line_items_path(:product_id => product) %> 
            

            在 application_helper 中

            def button_to(image_path, link)
              link_to (image_tag(image_path, :class => "img"), link)
            end
            

            我想这就是你想要的。

            【讨论】:

            • 这个创建链接,而不是按钮。我建议通过css创建按钮和样式
            • 按钮只能用于提交或重置表单。如果你只想要外观,那么你可以设置 标签的样式。
            • 最后的评论准确吗?我经常将非提交行为附加到按钮标签...
            • @jaydel 是的,但那将是您将使用 javascripts 而不是按钮标签的基本功能所做的事情。见w3schools.com/tags/tag_button.asp
            猜你喜欢
            • 2014-09-20
            • 2016-09-01
            • 2011-02-11
            • 2017-09-21
            • 1970-01-01
            • 2013-08-02
            • 1970-01-01
            • 2023-03-25
            • 1970-01-01
            相关资源
            最近更新 更多