javascript - 样式输入类型 ="file"- 没有出现 "No file selected"

标签 javascript html css input

我最近决定尝试为 input type="file" 设计样式。 设计几乎没问题,唯一的问题是我希望文本“No file selected”出现在 filename 选择中。即使我选择了一个文件,也没有文本出现。 我将不胜感激任何帮助和解释!

我有以下代码:HTML

<div class="fileuploader">
  <input type="text" class="filename" disabled="disabled" />
  <input type="button" name="file" class="filebutton" value="Browse" />
  <input type="file" name="avatar" />
</div>

和以下 CSS

.fileuploader {
    position: relative;
    display: inline-block;
    overflow: hidden;
    cursor: default;
}

.filename {
    float: left;
    display: inline-block;
    outline: 0 none;
    height: 30px;
    width: 302px;
    overflow: hidden;
    border: 1px solid #CCCCCC;
    color: #777;
    text-shadow: 1px 1px 0px #fff;
    border-radius: 5px 0px 0px 5px;
    box-shadow: 0px 0px 1px #fff inset;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    padding: 6px 10px;
}


    .filebutton {
        float: left;
        height: 30px;
        display: inline-block;
        outline: 0 none;
        cursor: pointer;
        border: 1px solid #CCCCCC;
        border-radius: 5px 5px 5px 5px;
        box-shadow: 0 0 1px #fff inset;
        color: #555555;
        margin-left: 3px;
        padding: 6px 12px;
        background: #DDDDDD;
        background:-moz-linear-gradient(top, #EEEEEE 0%, #DDDDDD 100%);
        background:-webkit-gradient(linear, left top, left bottom, color-stop(0%, #EEEEEE), color-stop(100%, #DDDDDD));filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#EEEEEE', endColorstr='#DDDDDD', GradientType=0);
    }

    .fileuploader input[type=file] {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        border: 0;
        height: 30px;
        cursor: pointer;
        filter:alpha(opacity=0);
        -moz-opacity: 0;
        -khtml-opacity: 0;
        opacity: 0;
        margin: 0;
        padding: 0;
    }

最佳答案

I want the text "No file selected" appear in the filename selection. Even when I select a file no text does appear.

一种解决方案是在文件输入触发 JavaScript“更改”事件时更新文件名。这可以使用 jQuery 的 $.change() 函数轻松完成:

$(document).ready(function() {
    $('input[type="file"]').change(function() {
        var val = ($(this).val()) ? $(this).val() : "No file selected.";
        $('.filename').attr('placeholder', val);
    });
});

http://api.jquery.com/change/

我创建了一个包含此功能的 jsFiddle:http://jsfiddle.net/cfY6m/1/

关于javascript - 样式输入类型 ="file"- 没有出现 "No file selected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17458756/

相关文章:

javascript - jQuery动画仅当ajax信息不相同时

css - 垂直调整窗口大小时 Div 容器消失

javascript - 流畅的动画没有滞后

javascript - 如何将 HTTPS 表单提交到 HTTPS 服务器

javascript - Bootbox 模式在打开前滚动到页面顶部

php - Jquery 在我的代码中设置输入键文本区域

java - 在java中使用html mailto href

javascript - 如何停止表单提交并抛出错误jquery

javascript - 正方形内的两个三 Angular 形可点击区域

html - 内联 block 在其容器的高度溢出?