在rails中定制f.file.field的外观 [英] customising the look of f.file.field in rails

查看:231
本文介绍了在rails中定制f.file.field的外观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    <div id="photo_attachment_container">
        <%= f.file_field :photo %>
    </div>

目前这只是一个按钮,我如何添加一些css和自定义外观背景等)这个按钮?感谢

Currently this just looks like a button, how can I add some css and customise the look (e.g dimensions background etc) of this button? Thanks

推荐答案

HTML文件字段已经并且仍然是HTML表单控件中最不可定制的一种。另一个问题是,它在浏览器和操作系统之间呈现如此不同。对这些控件进行风格化的最佳方式是将文件控件作为透明元素呈现在另一个按钮或者按照所需方式设置的元素集之上。文件控件不需要是可见的,可以通过用户点击激活,但它需要位于最上层(发送它的点击或焦点事件在我的测试中不起作用)。

The HTML file field has been, and remains, one of the most least customizable of the HTML form controls. The other problem is that it is rendered so differently between browsers and OSes. The best way to style these controls is to render the file control as a transparent element on top of another button or set of elements that is styled the way you want. The file control does not need to be visible to be activated with a user click, but it does need to be on the top most layer (sending it click or focus events doesn't work in my tests).

以下是一些HTML示例:

Here's some example HTML:

<div id="test">
    <div class="wrapper">
        <input type="file" />
    </div>
    <button>Select a file</button>
</div>

CSS将wrapper div和button作为绝对定位的元素。该按钮是可见的和样式化的,而包含文件字段的包装器是透明的。我已经设置了包装器字段以减少透明度,当您将鼠标悬停在其上以说明其相对于下面的样式按钮的位置。

The CSS renders the wrapper div and button as absolutely positioned elements. The button is visible and styled while the wrapper which contains the file field is transparent. I've set the wrapper field to reduce transparency when you hover over it to illustrate its positioning relative to the styled button underneath.

#test {
    position: relative;
}

#test .wrapper {
    opacity: 0;
    cursor: pointer;
    position: absolute;
    top: 0;
    z-index: 2;
}

#test .wrapper:hover {
    opacity: 0.5;
}

#test button {
    background-color: #ccc;
    border: none;
    color: #666;
    padding: 3px 5px;
    border-radius: 5px;
    position: relative;
    top: 0;
    z-index: 1;
}

JS小提琴的例子。

http://jsfiddle.net/JgDuh/

编辑:

要回答您在您的评论中提出的问题,您将在Rails视图模板中构造上述答案,如下所示:

To answer the question you asked in your comment, you would structure the above answer in your Rails view template like this:

<div id="photo_attachment_container">
  <div class="wrapper">
    <%= f.file_field :photo %>
  </div>
</div>

这将渲染为(注意,我使用 user 代替在 form_for 中传递的任何模型:

This would render as (Note that I used user as the substitute for whatever model you passed in form_for):

<div id="photo_attachment_container">
  <div class="wrapper">
    <input type="file" id="user_photo" name="user[photo]" />
  </div>
</div>

这篇关于在rails中定制f.file.field的外观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆