Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

javascript - 我可以在JavaScript中以编程方式为文件输入元素触发“点击”事件吗?(In JavaScript can I make a “click” event fire programmatically for a file input element?)

I'd like to make a click event fire on an <input type="file"> tag programmatically.

(我想以编程方式在<input type="file">标记上触发click事件。)

Just calling click() doesn't seem to do anything or at least it doesn't pop up a file selection dialog.

(仅调用click()似乎没有任何作用,或者至少它没有弹出文件选择对话框。)

I've been experimenting with capturing events using listeners and redirecting the event, but I haven't been able to get that to actually perform the event like someone clicked on it.

(我一直在尝试使用侦听器捕获事件并重定向事件,但是我无法像某些人单击它那样使它真正执行事件。)

  ask by user28655 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I have been searching for solution to this whole day.

(我整天都在寻找解决方案。)

And these are the conclusions that I have made:

(这些是我得出的结论:)

  1. For the security reasons Opera and Firefox don't allow to trigger file input.

    (出于安全原因,Opera和Firefox不允许触发文件输入。)

  2. The only convenient alternative is to create a "hidden" file input (using opacity, not "hidden" or "display: none"!) and afterwards create the button "below" it.

    (唯一方便的替代方法是创建一个“隐藏”文件输入(使用不透明度,而不是“隐藏”或“显示:无”!),然后在其下方创建按钮。)

    In this way the button is seen but on user click it actually activates the file input.

    (通过这种方式可以看到按钮,但是在用户单击时实际上会激活文件输入。)

Hope this helps!

(希望这可以帮助!)

:)

(:))

<div style="display: block; width: 100px; height: 20px; overflow: hidden;">
<button style="width: 110px; height: 30px; position: relative; top: -5px; left: -5px;"><a href="javascript: void(0)">Upload File</a></button>
<input type="file" id="upload_input" name="upload" style="font-size: 50px; width: 120px; opacity: 0; filter:alpha(opacity=0);  position: relative; top: -40px;; left: -20px" />
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...