我想通过编程方式在<input type="file">标记上生成一个点击事件。
仅仅调用click()似乎没有做任何事情,或者至少它不会弹出一个文件选择对话框。
我一直在尝试使用侦听器捕获事件并重定向事件,但我还不能像某人点击它那样实际执行事件。
我想通过编程方式在<input type="file">标记上生成一个点击事件。
仅仅调用click()似乎没有做任何事情,或者至少它不会弹出一个文件选择对话框。
我一直在尝试使用侦听器捕获事件并重定向事件,但我还不能像某人点击它那样实际执行事件。
当前回答
要做到这一点,你可以点击文件输入上的一个不可见的传递元素:
function simulateFileClick() {
const div = document.createElement("div")
div.style.visibility = "hidden"
div.style.position = "absolute"
div.style.width = "100%"
div.style.height = "100%"
div.style.pointerEvents = "none"
const fileInput = document.getElementById("fileInput") // or whatever selector you like
fileInput.style.position = "relative"
fileInput.appendChild(div)
const mouseEvent = new MouseEvent("click")
div.dispatchEvent(mouseEvent)
}
其他回答
这将在Firefox 4中实现,但需要注意的是,它被视为一个弹出窗口,因此无论何时弹出窗口都将被阻止。
以下是对我有用的解决方案: CSS:
#uploadtruefield {
left: 225px;
opacity: 0;
position: absolute;
right: 0;
top: 266px;
opacity:0;
-moz-opacity:0;
filter:alpha(opacity:0);
width: 270px;
z-index: 2;
}
.uploadmask {
background:url(../img/browse.gif) no-repeat 100% 50%;
}
#uploadmaskfield{
width:132px;
}
HTML与“小”JQuery帮助:
<div class="uploadmask">
<input id="uploadmaskfield" type="text" name="uploadmaskfield">
</div>
<input id="uploadtruefield" type="file" onchange="$('#uploadmaskfield').val(this.value)" >
只是要确保maskfied被true upload字段完全覆盖。
它是有效的:
出于安全原因,在Firefox和Opera上,你不能触发点击文件输入,但你可以用MouseEvents模拟:
<script>
click=function(element){
if(element!=null){
try {element.click();}
catch(e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
element.dispatchEvent(evt);
}
}
};
</script>
<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">
要做到这一点,你可以点击文件输入上的一个不可见的传递元素:
function simulateFileClick() {
const div = document.createElement("div")
div.style.visibility = "hidden"
div.style.position = "absolute"
div.style.width = "100%"
div.style.height = "100%"
div.style.pointerEvents = "none"
const fileInput = document.getElementById("fileInput") // or whatever selector you like
fileInput.style.position = "relative"
fileInput.appendChild(div)
const mouseEvent = new MouseEvent("click")
div.dispatchEvent(mouseEvent)
}
我有一个<input type="button">标签隐藏在视图中。我所做的是将“onClick”事件附加到任何类型的可见组件(如标签)。这是使用谷歌Chrome的开发工具或Mozilla Firefox的Firebug使用右键单击“编辑HTML”命令完成的。在这种情况下,指定以下脚本或类似的东西:
如果你有JQuery:
$('#id_of_component').click();
如果不是:
document.getElementById('id_of_component').click();
谢谢。