javascript - 您如何以编程方式告诉 HTML SELECT 下拉(例如,由于鼠标悬停)?

标签 javascript html

如何以编程方式告诉 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/

相关文章:

javascript - 同步 Sequelize 模型 : sequelize. import() 不是函数(并且已弃用)

javascript - 错误 TS2304 : Cannot find name '$event'

html - 将表格居中对齐

java - JSP输出前后的内容如何写

javascript - 处理从对象数组中抓取对象的更好方法?

javascript - 在容器外部单击时容器自动隐藏

javascript - 确保元素始终位于顶部

javascript - 使用 Angular x-editable 时如何通过 PUT 方法更新值?

javascript - 在没有提交按钮的情况下选中时如何获取复选框名称

javascript - 按下按钮时的水平和垂直不可见滚动