原生js实现鼠标点击效果(不是真实鼠标点击,用js模拟鼠标点击,类似jquery trigger效果)

时间:2022-12-22 18:10:41
<!DOCTYPE html>
<html>
<head>
<title>这是一个测试文件</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,
user-scalable=no">
</head>
<body>




<button id="target"></button>
<button id="resource">测试原生js触发事件</button>




<script type="text/javascript">


function trigger(node, event){


    if(document.all) {
        node.click();
    }else {
        var e = document.createEvent("MouseEvents");
        e.initEvent(event, true, true);              
        node.dispatchEvent(e);   
    }   
}


document.getElementById("resource").addEventListener("click", function(e){

trigger(document.getElementById("target"), "click");


},false);


document.getElementById("target").addEventListener("click", function(e){

console.log("我被点击了")


},false);







</script>






</body>


</html>