如何覆盖HTML select标签的onclick事件? [英] How to override onclick event of HTML select tag?
问题描述
我已经覆盖了select标签上的click事件。当我单击我的选择标记作为默认选项列表时,会显示选项列表。但是,当我点击选择标记时,我必须自定义该列表并执行其他工作。
I have overriden the click event on my select tag. When I click on my select tag as default the option list is showing. But I have to customize that listing and do some other work when I click on select tag.
我如何实现这一目标?
请参阅以下代码:
<!DOCTYPE html>
<html>
<body>
<select id="selectId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<script>
document.getElementById("selectId").onclick = function () {
alert("second event");
}
</script>
</body>
</html>
这两个事件都被解雇了,但我只想要第二个事件。
Here both event get fired, but I want only the second event.
推荐答案
您无法覆盖选择
元素 onClick
因为它没有。当您单击选择
时,浏览器会使用您无法调节的魔法来处理它。您无法模拟其上的点击。
You can't override the select
element onClick
because it doesn't have one. When you click on a select
the browser handles it with magic that you can't temper with. You can't simulate a click on it either.
您可以对选择做的唯一事情是:
The only things you can do to a select are:
- 更改其
size
属性。您可以将其更改为1
以强制关闭,但您会看到一个丑陋的闪烁。 - set
隐藏
属性,所有子选项
元素到true
- change its
size
property. You can change it to1
to force it to close, but you will see an ugly flicker. - set
hidden
property on all childoption
elements totrue
你可以假装它,如下所示:
You can fake it, something like this:
HTML:
<div class="wrapper">
<select id="selectId" size="2" multiple="true">
<option value="volvo" hidden="true">Volvo</option>
<option value="saab" hidden="true">Saab</option>
<option value="opel" hidden="true">Opel</option>
<option value="audi" hidden="true">Audi</option>
</select>
<div class="mask">Volvo</div>
</div>
Javascript:
Javascript:
$('.wrapper').click( function(event){
console.log("sdsd");
if(true){
$('#selectId').show();
$(".mask").hide();
}
event.stopPropagation();
});
$('body').click(function(){
$('#selectId').hide();
$(".mask").show();
});
CSS:
.mask{
position:absolute;
top:0;
width:100%;
height:100%;
text-align:center;
}
.wrapper{
position:relative;
display:inline-block;
min-height:23px;
min-width:62px;
vertical-align:top; overflow:hidden; border:solid grey 1px;
}
#selectId{
display:none;
padding:20px;
margin:-18px -30px -18px -8px;
}
这只是一个起点。你可以从这里建造。
This is only a starting point. You can build from here.
这篇关于如何覆盖HTML select标签的onclick事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!