你如何风格输入类型=“文件”按钮?

<输入类型=“文件” />


当前回答

不要被“伟大的”css解决方案所欺骗,这些解决方案实际上非常特定于浏览器,或者将样式化按钮覆盖在真正的按钮之上,或者强迫您使用<label>而不是<button>,或任何其他类似的hack。JavaScript是必要的,以使其工作为一般用途。如果你不相信我,请学习gmail和DropZone是怎么做的。

只要按你想要的样式设计一个普通的按钮,然后调用一个简单的JS函数来创建并链接一个隐藏的输入元素到你的样式按钮。

<!DOCTYPE html>
<meta charset="utf-8">

<style>
    button {
        width            : 160px;
        height           : 30px;
        font-size        : 13px;
        border           : none;
        text-align       : center;
        background-color : #444;
        color            : #6f0;
    }
    button:active {
        background-color : #779;
    }
</style>

<button id="upload">Styled upload button!</button>

<script>

function Upload_On_Click(id, handler) {
    var hidden_input = null;
    document.getElementById(id).onclick = function() {hidden_input.click();}
    function setup_hidden_input() {
        hidden_input && hidden_input.parentNode.removeChild(hidden_input);
        hidden_input = document.createElement("input");
        hidden_input.setAttribute("type", "file");
        hidden_input.style.visibility = "hidden";
        document.querySelector("body").appendChild(hidden_input);
        hidden_input.onchange = function() {
            handler(hidden_input.files[0]);
            setup_hidden_input();
        };
    }
    setup_hidden_input();
}

Upload_On_Click("upload", function(file) {
    console.log("GOT FILE: " + file.name);
});

</script>

注意上面的代码是如何在用户每次选择一个文件后重新链接它的。这很重要,因为只有当用户更改文件名时才会调用"onchange"。但您可能希望在用户每次提供该文件时获取该文件。

其他回答

这种方法为您提供了完全的灵活性!ES6 / VanillaJS!

html:

<input type="file" style="display:none;"></input>
<button>Upload file</button>

javascript:

document.querySelector('button').addEventListener('click', () => {
  document.querySelector('input[type="file"]').click();
});

这隐藏了输入文件按钮,但实际上是从另一个普通按钮点击它,显然您可以像设置其他按钮一样设置它的样式。这是除了无用的dom节点之外没有任何缺点的唯一解决方案。多亏了display:none;,输入按钮在DOM中不保留任何可见空间。

(我已经不知道该支持谁了。但我是从Stackoverflow网站的某个地方得到这个想法的。)

一个图像上传应用程序的演示,适用于大多数后端良好的动画功能。

// common function render_element(styles, el) { for (const [kk, vv] of Object.entries(styles)) { el.style[kk] = vv; } } function hoverOpacity(el) { el.addEventListener('mouseenter', function() { el.style.opacity = 0.75 }.bind(el)); el.addEventListener('mouseleave', function() { el.style.opacity = 1 }.bind(el)); } // return void event handler on setTimeout function buffer(func, time){ return e=>{ if(func.still)return; // first runtime if(!func.pft){ func(e); func.pft = true; func.still = false; return; } func.still = true; setTimeout(e=>{ func(e); func.still = false; }, time); } } // end of common const imageUploadButton = document.getElementById('image-upload-button'); imageUploadButton.addEventListener('click', e=>{ // pulse animation total time const d1 = document.getElementById('image-form'); let time = 600; if(d1.rendered){ d1.ready(); }else{ d1.ready = function(){ d1.style.display = 'flex'; d1.style.background = '#c5edd0'; this.d2.style.background = '#b4dbbf'; this.d3.style.background = '#95dea9'; this.d4.innerHTML = 'Drag and Drop or Click Above to Upload'; } let dismiss_btn = document.createElement('div'); render_element({ position: 'absolute', height: '30px', width: '30px', top: '0', right: '0', background: '#fff', borderRadius: '30px', cursor: 'pointer', margin: '2px', zIndex: '10', }, dismiss_btn); dismiss_btn.addEventListener('mouseenter', function(){this.style.background = '#fc4f30'}); dismiss_btn.addEventListener('mouseleave', function(){this.style.background = '#fff'}); dismiss_btn.addEventListener('click', ()=>{d1.style.display = 'none'}); d1.appendChild(dismiss_btn); const d3 = d1.querySelector('#image-input'); const d5 = d1.querySelector('#image-submit'); d5.style.visibility = 'hidden'; d1.parentNode.removeChild(d1); document.body.appendChild(d1); d1.removeChild(d3); let [ d2, d4, ] = Array.from({length: 3}, ()=>document.createElement('div')); let width = window.innerWidth; let d_styles = { display: 'flex', justifyContent: 'center', alignItems: 'center', }; render_element({ position: 'fixed', left: ((width - 430) / 2).toString() + 'px', width: '430px', top: '60px', height: '280px', zIndex: '10', }, d1); render_element(d_styles, d1); render_element({ width: '90%', height: '90%', }, d2); render_element(d_styles, d2); render_element({ width: '80%', height: '70%', fontSize: '0', cursor: 'pointer', }, d3); hoverOpacity(d3); render_element(d_styles, d3); d1.appendChild(d2); d2.appendChild(d3); let tt = time / 3; let ht = tt / 2; d1.addEventListener('dragover', buffer(e=>{ d1.style.background = '#ebf9f0'; setTimeout(()=>{ d1.style.background = '#95dea9'; }, ht); setTimeout(()=>{ d2.style.background = '#b6e3c2'; setTimeout(()=>{ d2.style.background = '#c4eed2'; }, ht); }, tt); setTimeout(()=>{ d3.style.background = '#cae3d1'; setTimeout(()=>{ d3.style.background = '#9ce2b4'; }, ht); }, tt); }, time)); d2.style.flexDirection = 'column'; render_element({ fontSize: '16px', textAlign: 'center', fontFamily: 'Verdana', }, d4); d2.appendChild(d4); d3.addEventListener('change', e=>{ // backend // d5.click(); // if backend succeed, run frontend setTimeout(()=>{ d1.style.background = '#dbcea2'; setTimeout(()=>{ d2.style.background = '#dbc169'; setTimeout(()=>{ d3.style.background = '#ebc034'; }, ht); }, tt); }, time); // display backend path here // now only display filename d4.innerHTML = d3.files[0].name; }); d1.d2 = d2; d1.d3 = d3; d1.d4 = d4; d1.ready(); d1.rendered = true; } }); #image-upload-button{ width: 200px; height: 40px; background: lightgrey; display: flex; align-items: center; justify-content: center; cursor: pointer; } #image-form{ display: none; } ::-webkit-file-upload-button { visibility: hidden; } <div id="image-upload-button">Upload Image <form id="image-form" action="post"> <input id="image-input" type="file" /> <button id="image-submit" type="submit"></button> </form> </div>

这里有一个简单的css解决方案,它创建了一个一致的目标区域,并让你的伪造元素的风格,无论你喜欢。

基本思想是这样的:

有两个“假”元素(一个文本输入/链接)作为你的真实文件输入的兄弟。绝对放置它们,让它们完全在你的目标区域上方。 用div包装你的文件输入。将overflow设置为hidden(这样文件输入就不会溢出来),并使它恰好是你想要的目标区域的大小。 在文件输入上设置不透明度为0,这样它就被隐藏了,但仍然可以点击。给它一个大的字体大小,这样你就可以点击目标区域的所有部分。

下面是jsfiddle: http://jsfiddle.net/gwwar/nFLKU/

<form>
    <input id="faux" type="text" placeholder="Upload a file from your computer" />
    <a href="#" id="browse">Browse </a>
    <div id="wrapper">
        <input id="input" size="100" type="file" />
    </div>
</form>

用css隐藏它,并使用$(selector).click()自定义按钮来激活浏览按钮。然后设置检查文件输入类型值的时间间隔。interval可以显示用户的值,这样用户就可以看到上传了什么。当表单提交时,间隔将清除[编辑]对不起,我一直很忙,是想更新这篇文章,这里是一个例子

<form action="uploadScript.php" method="post" enctype="multipart/form-data">
<div>
    <!-- filename to display to the user -->
    <p id="file-name" class="margin-10 bold-10"></p>

    <!-- Hide this from the users view with css display:none; -->
    <input class="display-none" id="file-type" type="file" size="4" name="file"/>

    <!-- Style this button with type image or css whatever you wish -->
    <input id="browse-click" type="button" class="button" value="Browse for files"/>

    <!-- submit button -->
    <input type="submit" class="button" value="Change"/>
</div>

$(window).load(function () {
    var intervalFunc = function () {
        $('#file-name').html($('#file-type').val());
    };
    $('#browse-click').on('click', function () { // use .live() for older versions of jQuery
        $('#file-type').click();
        setInterval(intervalFunc, 1);
        return false;
    });
});

如果有人仍然关心如何在没有JavaScript的情况下做到这一点,让我完成Josh的回答:

如何显示文件名的文本:

最简单的方法是将这两个元素设置到一个位置:相对,给标签一个更高的z-index,并给输入文件负边距,直到标签文本在你想要的位置。不要在输入时使用display:none !

例子:

input[type="file"] {
  position:relative;
  z-index:1;
  margin-left:-90px;
}

.custom-file-upload {
  border: 1px solid #ccc;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer;
  position:relative;
  z-index:2;
  background:white;

}