JS onClick preventDefault输入

时间:2020-01-09 14:38:29

标签: javascript html onclick

如何防止<input>的默认onClick行为?

document.getElementById("main").onclick = function() {
  document.getElementById("main").style.backgroundColor = "red";
}
#main {
  background-color: blue;
}
<div id="main">
  If you click here, change background to red.
  <input id="search" type="search" value="If you click here, do nothing.">
</div>

工作示例:https://jsfiddle.net/7bng6zuh/3/

2 个答案:

答案 0 :(得分:1)

要防止您的div在单击输入时更改其背景并且仅在直接单击div时才更改其背景,只需将事件 target 与事件当前目标进行比较>(添加了点击侦听器的元素)并仅在目标与当前目标相同的情况下才更改div css,如下所示:

const mainDiv = document.getElementById("main");

function checkClick(e) {
	if (e.target === e.currentTarget) { // check if element clicked is the div itself or some other element in the div.
  	mainDiv.style.backgroundColor = "red";
  }
}

mainDiv.addEventListener('click', checkClick);
#main {
  background-color: blue;
}
<div id="main">
  If you click here, change background to red. 
  <input id="search" type="search" value="If you click here, do nothing.">
</div>


事件目标:您单击的元素。

事件当前目标:点击监听器正在监听的元素。

答案 1 :(得分:0)

检查目标

document.getElementById("main").addEventListener("click",function(e) {
  if (e.target.id && e.target.id  === "main") { // or e.target === e.currentTarget
    this.style.backgroundColor = "red";
  }
});
#main {
  background-color: blue;
}
<div id="main">
  If you click here, change background to red. 
  <input id="search" type="search" value="If you click here, do nothing.">
</div>