简体   繁体   English

输入[type='file'] 标签名称

[英]Input[type='file'] label name

I am trying to modify the look of an input[type='file'] element which I have done,我正在尝试修改我已经完成的 input[type='file'] 元素的外观,

<div class="own_image_wrapper">
  <%= f.label :image, id: 'own-image-label', class: 'lato-font fileContainer image_button' do %>
  Choose Your Own
  <%= f.file_field :image %>
 <% end %>
</div>

CSS CSS

.fileContainer {
  overflow: hidden;
  position: relative;
}

.fileContainer input[type='file'] {
  cursor: inherit;
  display: block;
  font-size: 999px;
  filter: alpha(opacity=0);
  min-height: 100%;
  min-width: 100%;
  opacity: 0;
  position: absolute;
  right: 0;
  text-align: right;
  top: 0;
}

.image_button{
  padding:15px;
  color:$white;
  background:$blue;
  text-transform:uppercase;
}

The next stage for me is to change the label text once a user selects a file, my first issue is that the event doesn't always fire, leaving a button with no content.我的下一阶段是在用户选择文件后更改标签文本,我的第一个问题是事件并不总是触发,留下一个没有内容的按钮。

$(document).ready( function() {
// Update Choose your own image label with file name
$( '#own-image-label [type=file]' ).on( 'click', function (){
  var $input = $( this );

  setTimeout( function (){
     $input.parent().text( $input.val().replace(/([^\\]*\\)*/,'') )
   }, 0 )
  } );

});

and when it does fire I can't click the input any more as the following has been removed from the DOM:当它触发时,我无法再单击输入,因为以下内容已从 DOM 中删除:

<input id="campaign_image" type="file" name="campaign[image]">

and secondly how can I stop the input type['file'] from being removed from the DOM?其次,如何阻止输入类型 ['file'] 从 DOM 中删除?

Edit编辑

This is the markup before这是之前的标记

<label id="own-image-label" class="lato-font fileContainer image_button" for="campaign_image">
  Choose Your Own
  <input id="campaign_image" type="file" name="campaign[image]">
</label>

And then if I select a file called myfile.jpg this is the markup然后如果我选择一个名为 myfile.jpg 的文件,这就是标记

<label id="own-image-label" class="lato-font fileContainer image_button" for="campaign_image">myfile.jpg</label>

When you set the text of the label , it overwrites its current contents.当您设置label的文本时,它会覆盖其当前内容。 You need to target the text node itself, and set the value of that:您需要定位文本节点本身,并设置其值:

this.parentNode.childNodes[0].nodeValue = $input.val().replace(/([^\\]*\\)*/,'');

You must ensure that the DOM is ready before you attempt to attach the handler, otherwise it may not be attached.在尝试附加处理程序之前,您必须确保 DOM 已准备好,否则可能无法附加。 Also, it doesn't look to me like your setTimeout() serves any purpose.此外,在我看来,您的setTimeout()没有任何用途。 If you don't need it for any specific reason, you can remove it.如果出于任何特定原因不需要它,则可以将其删除。

Here's a fiddle这是一把小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM