如何使用CSS将“<input type =” file“/>”制作成链接样式?

13

只是想改变风格:

<input type="file" value="Choose the file" />

看起来像:

<a href="#">Choose the file</a>

只使用CSS,是否可能实现这个效果?


2
从经验来看,这是一个非常难以样式化的元素,特别是在旧版本的浏览器中。 - Paddy
你想将“文件”按钮样式设置为链接吗? - M Zeinstra
1
像这个吗?https://dev59.com/OlzUa4cB1Zd3GeqPzAMW#18716005 - chris
5个回答

22

3
我认为此帖子中有很多非常聪明的技巧和解决方法,但在我看来,这绝对是最优雅的答案。 - John Weisz
2
我一直有困扰如何为 input[type="file"] 设置样式,而这个解决方案在我看来是最好的。 - Vucko
是的,这是正确的答案。坚持使用表单元素;干净简洁。不需要任何黑客技巧。 - misterManSam
如果您只想要一个链接的外观,而没有任何多余的用户界面,那么这绝对是正确的方法。 - SW4

10

可能需要对大小、悬停状态等进行微调,但为什么不这样做呢:

span {
  cursor: pointer;
}
a {
  position: relative;
  overflow: hidden;
}
span:hover a {
  color: red;
}
a + input {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
}
<span><a href='#'>Link!</a><input type='file' /></span>

基本原则是将 input type=file 定位在链接上方并将其不透明度设置为零,以便它仍然可以捕获正常的用户交互行为。

2
不错的解决方案,但是在a标签内放置一个input是无效的。 - putvande
@putvande - 完全正确,这只是为了演示目的,但出于准确性的考虑,我已进行了编辑 :) +1 - SW4
最后一个span标签不应该是闭合标签吗? - Mario Flores

1
你可以添加一个与输入框相关联的标签(无论如何,出于可访问性的考虑,你都应该这样做,尤其是你真的需要隐藏输入框)。然后,你可以将输入框的opacity设置为0,并使其成为position:absolute,以便它不影响页面。你可以隐藏它,但我认为一些浏览器将不会触发标签功能,因此你将无法选择文件。
然后,你可以按照自己的喜好对标签进行样式设置,甚至将其包装在a标签中,这样它就会像页面上的其他链接一样运作。
隐藏输入框的缺点是你将无法看到所选文件。如果你需要这样做,你可以使用一小段jquery代码在标签中显示它:

$('input[type="file"]').change(function() {
  // find the label for the currrent file input 
  $('label[for="' + this.id + '"]').text('Choose the file - ' + $(this).val());
});
input[type=file] {
  position: absolute;
  top: 0;
  right: 0;
  filter: alpha(opacity=0);
  opacity: 0;
  margin: 0;
  padding: 0;
}

a > label {
  /* inherit the hand cursor from the a tag */
  cursor:inherit;
}

a:hover {
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#">
    <input id="thefile" type="file" value="Choose the file" />
    <a href="#"><label for="thefile">Choose the file</label></a>
</form>


0

input 标签放在 a 标签内是无效的。 - putvande
请在您的代码中添加一些说明,展示它如何解决问题,这将有助于未来的读者。 - Our Man in Bananas

0

这里有另一种类似于上面的解决方案,但我将输入标签分开并显示链接。

div.fileinputs {
    position: relative;
}

div.fakefile {
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 1;
}

input.file {
  position: relative;
  text-align: right;
  -moz-opacity:0 ;
  filter:alpha(opacity: 0);
  opacity: 0;
  z-index: 2;
}

还有HTML

<div class="fileinputs">
  <input type="file" class="file" />
  <div class="fakefile">
    <a href="">browse file</a>
  </div>
</div>

这里是fiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接