简体   繁体   English

选择元素的Click(鼠标按下)事件

[英]Click (mousedown) event of a select element

I have an empty select element, I want to execute some code when that element is clicked on, but I do not want the dropdown list to appear, here is what I have found: 我有一个空的select元素,我想在单击该元素时执行一些代码,但是我不希望出现下拉列表,这是我发现的内容:

  1. When I disabled the select element I cannot catch the mousedown event. 禁用选择元素时,无法捕获mousedown事件。
  2. When I enable the select element I can capture the mousedown event but the dropdown list appears. 启用select元素时,我可以捕获mousedown事件,但会出现下拉列表。

For arguements sake what I want is to be able to click the select element, JavaScript to throw an alert box but I want to prevent the dropdown list from displaying. 为了争辩,我想要的是能够单击select元素,JavaScript引发一个警报框,但是我想阻止显示下拉列表。

Thanks! 谢谢!

capture onmousedown event of select element and cancel the event by setting event.returnValue to false. 捕获select元素的onmousedown事件,并通过将event.returnValue设置为false来取消该事件。

<script type="text/javascript">
    function onSelectMouseDown() {
        event.returnValue = false;
        alert("mouse down caught and cancelled");
    }
</script>

<select id="select" onmousedown="onSelectMouseDown();"></select>

为什么不禁用select元素,然后将select元素包装在与select元素高度和宽度相同的div(或其他宽度)中,并在此div中使用mousedown事件?

<script>
function makeDisable(){
    var x=document.getElementById("mySelect")
    x.disabled=true
}
function makeEnable(){
    var x=document.getElementById("mySelect")
    x.disabled=false
}
function f() {
makeDisable();
alert("something");
t=setTimeout("makeEnable();",1);
}
</script>

<select id="mySelect" onMouseDown="f();">
  <option value="opt1">Option 1</option>
  <option value="opt2">Option 2</option>
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在“ mousedown”事件期间添加新元素会阻止触发“ click”事件? - Adding New Element during `mousedown` event prevent triggering `click` event? 当 mousedown/mouseup 在元素上添加/删除类时不发出单击事件 - Click event not emitted when mousedown/mouseup do add/removeClass on element 防止 mousedown 的点击事件 - Prevent click event from mousedown HTML select 元素上的单击事件 - click event on HTML select element 链接点击事件被父mousedown事件阻止 - Link click event blocked by parent mousedown event 在 mousedown 和 mouseup 事件之后防止单击事件 - Prevent click event after mousedown & mouseup event 问题停止点击事件 Function 在鼠标按下事件 - Problem To Stop Click Event Function On Mousedown Event 即使元素在 mousedown 和 mouseup 之间从光标下方移动,如何处理“单击”事件? - How to handle "click" event even if element is moved from beneath the cursor between mousedown and mouseup? 单击禁用的select元素不会触发其父级上的click或mousedown事件 - Clicking disabled select element doesn't trigger click or mousedown events on it's parent 动态将选择元素添加到div,mousedown事件可防止下拉菜单打开 - Dynamically add a select element to div, mousedown event prevents dropdown from opening
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM