Input [type ='file']标签名称

问题描述 投票:1回答:1

我正在尝试修改已完成的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

.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;
}

对我来说,下一个阶段是用户选择文件后更改标签文本,我的第一个问题是该事件并不总是触发,留下没有内容的按钮。

$(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 )
  } );

});

并且当它触发时,我无法再单击输入,因为以下内容已从DOM中删除:

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

其次我该如何阻止将输入类型['file']从DOM中删除?

编辑

这是之前的标记

<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>

然后,如果我选择一个名为myfile.jpg的文件,则为标记

<label id="own-image-label" class="lato-font fileContainer image_button" for="campaign_image">myfile.jpg</label>
javascript jquery css ruby-on-rails
1个回答
1
投票

设置label的文本时,它会覆盖其当前内容。您需要定位文本节点本身,并设置其值:

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

在尝试附加处理程序之前,必须确保DOM已准备就绪,否则可能无法附加。另外,在我看来,您的setTimeout()没有任何作用。如果出于任何特定原因不需要它,可以将其删除。

Here's a fiddle

© www.soinside.com 2019 - 2024. All rights reserved.