1.input元素的事件触发顺序

<!DOCTYPE html>
 <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title
  </head>
  <body>
    <input type="file" id="input">
  </body>
  <script>
   var num = 0;
  document.getElementById("input").addEventListener("focus",function () {
  console.log("focus");
  });
  document.getElementById("input").addEventListener("mousedown",function () {
    console.log("mousedown");
  });
  document.getElementById("input").addEventListener("mouseup",function () {
    console.log("mouseup");
  });
  document.getElementById("input").addEventListener("input",function () {
    console.log("input");
  });
  document.getElementById("input").addEventListener("change",function () {
    console.log("change");
    console.log(document.getElementById("input").value);
    console.log(document.getElementById("input").name);
   //document.getElementById("input").value = ‘’;
  });
  document.getElementById("input").addEventListener("blur",function () {
    console.log("blur");
  });
  document.getElementById("input").addEventListener("click",function () {
    console.log("click");
  });
 </script>
</html>

在上述例子中,input元素绑定了mousedown、mouseup、click、input、change、focus、blur等事件,经测试,事件触发的顺序如下:
(1)mousedown
(2)focus
(3)mouseup
(4)click
(5)blur
(6)focus
(7)change
  首先触发了鼠标按下事件,然后就是焦点到了input上面,然后鼠标抬起,触发click点击事件,失去焦点以后弹出了文件选择框,选中文件以后触发焦点,最后触发的change事件。
如果再次上传最近一次上传过的文件,则change事件不会触发。经测试,将value=‘’,再次上传最近一次上传过的文件则可以触发change事件(注意value只能赋值为空,其他值会报错)。在前端涉及到上传图片时可以利用这点来实现多次上传同一个文件。

2.Change事件触发条件

在将input type=file 上传文件后,将其value属性赋值不为空时,会报错:Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string. 未捕获的DOM异常:未能在“htmlinputeElement”上设置“value”属性:此输入元素接受一个文件名,该文件名只能以编程方式设置为空字符串。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐