为什么这个简单的例子不起作用?
<input id="image" type="file"/>
<img src='https://cdn.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png' onclick='imageLoad()'></img>
<script>
function imageLoad() {
let ev = new Event('click', {bubbles: true});
image.dispatchEvent(ev);
}
</script>
某些安全隐患适用是正确的,但根据您的目标,如果您将Event
构造函数更改为MouseEvent
,它将在本例中起作用。
...
<body>
<input id="image" type="file" />
<img id="handle" src="https://cdn.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png" />
<script>
let handle = document.getElementById('handle');
handle.addEventListener('click', imageLoad, false);
function imageLoad() {
let ev = new MouseEvent('click', {bubbles: true});
image.dispatchEvent(ev);
}
</script>
...
只是重复Peter Pajchl
,对于后面的人:
<!-- an ugly file input (quick, hide it away!) -->
<input
type="file"
id="htmlFileInputElement"
style="position: absolute; top: -1000px; left: -1000px;"
/>
<!-- a beautiful, inviting button -->
<button onclick="
htmlFileInputElement.dispatchEvent(
new MouseEvent('click', { bubbles: true })
)
">Upload File</button>
(因为此页面是设置文件输入样式和所有内容的第一搜索命中)
首先,检查<img>
关闭标签。其次,由于浏览器的安全原理,你不能通过 js 调度输入的点击事件。对于div,没问题:
function imageLoad() {
let image = document.querySelector('#div');
let ev = new Event('click', {bubbles: true});
image.dispatchEvent(ev);
}
function clickDiv(){
console.log('clicked the div');
}
<input id="image" type="file" />
<div id="div" onclick="clickDiv()">123</div>
<img src='https://cdn.elegantthemes.com/blog/wp-content/uploads/2015/02/custom-trackable-short-url-feature.png' onclick='imageLoad()' />