需求:点击输入框,显示下拉框,在输入框和下拉框区域鼠标右击时,下拉框保持显示状态,点击其他区域则消失。
原理很简单,给input绑定点击事件,点击后下拉框block,阻止input冒泡,点击document下拉框none。在chrome下这样做没问题,但是在firefox鼠标右键时,会触发click事件,即使阻止了冒泡也没用,解决方法是判断鼠标按键
demo code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>点击其它地方关闭DIV</title>
</head>
<body>
<input type="text" value="" id="text" />
<div style="width:400px; height:200px;border:1px solid #000;display:none" id="con">
<p>1111</p>
<p><span>2222</span></p>
<p>3333</p>
</div>
<script>
function e(obj) {
return document.getElementById(obj)
}
e(‘text‘).onclick = function(event) {
e(‘con‘).style.display = ‘block‘;
stopBubble(event);
}
// 点击con不消失
e(‘con‘).onclick = function(event) {
e(‘con‘).style.display = ‘block‘
stopBubble(event);
}
document.onclick = function(event) {
if (event.button === 2) {
e(‘con‘).style.display = ‘block‘;
} else {
e(‘con‘).style.display = ‘none‘;
}
}
//阻止冒泡函数
function stopBubble(event) {
if (event.stopPropagation) {
event.stopPropagation()
} else if (window.event) {
window.event.cancelBubble = true
}
}
</script>
</body>
</html>