如何以编程方式告诉 HTML select
下拉(例如,由于鼠标悬停)?
最佳答案
这在过去实际上可以通过 HTML+Javascript 实现,尽管其他地方的人都说它不是,但后来它被弃用了,现在不起作用。
但是,这只适用于 Chrome。如果您有兴趣,请阅读更多内容。
根据 W3C Working Draft for HTML5, Section 3.2.5.1.7. Interactive Content :
Certain elements in HTML have an activation behavior, which means that the user can activate them. This triggers a sequence of events dependent on the activation mechanism [...] for instance using keyboard or voice input, or through mouse clicks.
When the user triggers an element with a defined activation behavior in a manner other than clicking it, the default action of the interaction event must be to run synthetic click activation steps on the element.
<select>
作为一个交互式内容,我相信可以以编程方式显示它的 <option>
秒。玩了几个小时后,我发现使用 document.createEvent()
和 .dispatchEvent()
有效。
就是说,演示时间。 Here is a working Fiddle.
HTML:
<select id="dropdown">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br>
<button id="fire" type="button" onclick="runThis()">Show dropdown items</button>
Javascript:
// <select> element displays its options on mousedown, not click.
showDropdown = function (element) {
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
element.dispatchEvent(event);
};
// This isn't magic.
window.runThis = function () {
var dropdown = document.getElementById('dropdown');
showDropdown(dropdown);
};
如果有人找到一种方法来做同样的事情但不是在 Chrome 中,please feel free to modify this fiddle .
关于javascript - 您如何以编程方式告诉 HTML SELECT 下拉(例如,由于鼠标悬停)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/249192/