JS - 无法在Safari中将输入类型更改为FILE

Lim*_*nte 4 javascript safari input

[的jsfiddle]

除了Safari之外,代码在每个浏览器中都能正常工

在此输入图像描述

由于未知原因,Safari无法动态更改输入类型file.

首先:为什么会这样?

然后,是否有任何workaroud可以file在Safari中动态更改输入类型?

HiD*_*Deo 5

我只在Safari和旧版本的IE上看到过这个问题.关于原因,我从未在此事上找到任何记录.

有一次,jQuery本身禁止对type属性的更改,input因为它在IE中引起了问题.它被记录为:

// We can't allow the type property to be changed (since it causes problems in IE)
if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
  throw "type property can't be changed";
Run Code Online (Sandbox Code Playgroud)

你可以找到关于这个问题的更多信息这个问题.

如今,似乎不再是这种情况,但是在将类型更改为时,Safari仍然无声地失败file.另一方面,从file工作中改变它没有任何问题.由于没有记录,我一直认为这是为了"安全"措施,但我从来没有找到任何具体的证据.

我正在使用的解决方法是检测新类型的时间file,在这种特殊情况下,创建一个新input元素,将其类型设置为file,设置其id并用新的输入替换现有输入.

var input = $('#input');

$('button[id^=type-]').on('click', function() {
  var type = $(this).attr('id').replace('type-', '');

  if (type === 'file') {
    var newElement = document.createElement('input');
    newElement.type = type;
    newElement.id = input.attr('id');

    input.replaceWith(newElement);
    input = $('#input');
  } else {
    input.attr('type', type);
  }

  $('#debug-info').html(
    'Trying to change the input type to <strong>' + type + '</strong>.<br>' +
    'Actual input type is <strong>' + input.attr('type') + '<strong>.'
  );

  if (type == input.attr('type')) {
    $('#debug-info').css('color', 'green');
  } else {
    $('#debug-info').css('color', 'red');
  }
});
Run Code Online (Sandbox Code Playgroud)

你可以用这个小提琴来检查它.