firefox 错误 - 选项在悬停时消失

firefox bug - Options disappeared on hover

当我在 mouseenter 事件中插入 select 框时,Firefox 出现了错误。整个下拉列表悬停了。我该如何修复这个错误?

document.querySelector('#test').addEventListener('mouseenter',function(){
    this.innerHTML = '<select><option value=1>2</option><option value=2>3</option></select>';
});
#test{
    width: 100px;
    height: 100px;
    background-color: #000;
}
<div id="test"></div>

我也不能 select Chrome 中的值,所以我认为这不仅仅是 Firefox 的错误。

无论如何,这是一个修复程序。只需在 select 未加载鼠标输入时加载它。

 document.querySelector('#test').addEventListener('mouseenter',function(){
  if(this.innerHTML===""){  
    this.innerHTML = '<select><option value=1>2</option><option value=2>3</option></select>';}
    });

这是一种替代方法,我们可以在其中附加到 <div> 元素。在这个例子中,mouseenter 可能会触发很多,所以我将这段代码包装在一个闭包中以执行一次以演示附加一次。你当然可以根据你的需要制作它,但这种方法应该比覆盖元素

的 html 允许更多的功能

JSFiddle Link

var append = (function(ele, node) { // execute once closure
    var executed = false;
    return function (ele, node) {
        if (!executed) {
            executed = true;
            ele.appendChild(node);
        }
    };
})();

document.querySelector('#test').addEventListener('mouseenter', function() {
    var that = this;
    var node = document.createElement('select');
    node.innerHTML = '<option value=1>2</option><option value=2>3</option>'
    append(that, node);
});