[英]Simulating click event on input - JavaScript
我正在尝试通过单击anchor
标记来模拟对输入标记的单击,这样我就可以隐藏输入并将图像包裹在锚标记内。
这可以使用 jQuery 触发器函数工作,但我无法仅使用“普通”Javascript:
jQuery 版本:
let fake = $('.fake') fake.click(function(e) { e.preventDefault(); $('#user_avatar').trigger('click'); })
#user_avatar { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" name="file_field" id="user_avatar"> <a href="#" class="fake"> <img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240"> </a>
JavaScript 版本使用new Event
和dispatchEvent
:
let fake = document.querySelector('.fake'); fake.addEventListener('click', function(e) { e.preventDefault(); console.log('testing'); let clickEvent = new Event('click'); document.getElementById('user_avatar').dispatchEvent(clickEvent) })
#user_avatar { display: none; }
<input type="file" name="file_field" id="user_avatar"> <a href="#" class="fake"> <img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240"> </a>
已呈现 console.log,但未分派事件,我做错了什么?
用:
document.getElementById('user_avatar').click();
经测试,它有效。
document.getElementById('user_avatar').click()
将起作用
let fake = document.querySelector('.fake'); fake.addEventListener('click', function(e) { e.preventDefault(); document.getElementById('user_avatar').click() })
#user_avatar { display: none; }
<input type="file" name="file_field" id="user_avatar"> <a href="#" class="fake"> <img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240"> </a>
你根本不需要 JavaScript 来解决这个问题。
只需通过设置其opacity:0
使输入不可见,并将两个元素绝对放置在一个公共父元素内,然后确保输入位于顶层并且与后面的图像大小相同。
#user_avatar { opacity:0; position:absolute; z-index:9; width:320px; height:240px; } img { position:absolute; z-index:-1; }
<div> <input type="file" name="file_field" id="user_avatar"> <img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.