显示选择选项时的JavaScript事件?

时间:2016-09-22 01:42:41

标签: javascript jquery html drop-down-menu

<select>元素显示/隐藏其<options>列表时会触发哪些事件(如果有)?

示例:

<select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

当您用鼠标点击此选择框时,浏览器会显示选项列表。

但是,当您在选择框中选择标签时,浏览器不会显示选项列表。

检查select元素中的mouseup事件是唯一的方法,还是我错过了一些明显的东西?

$(document.body).on('mouseup', 'select', function(){            
    console.log('Either shown or hidden the options...but which?')
});

提前致谢。

P.S。我试图在显示<select>时向<options>元素添加一个类,这样当浏览器显示&#34;选项popover时,我可以显示不同的自定义插入符号样式&# 34;而不是它不是。

1 个答案:

答案 0 :(得分:0)

这意味着select元素处于焦点。所以在这种情况下你不需要javascript。您可以使用css来满足这一需求。

select:focus {
  color:red;
}

但是如果你确实想使用jquery,它会看起来像这样:

$("select").focus(function(){
  console.log(" h1 ");
})

使用纯粹的javascript,给你的选择一个id =“select”,你可以做这样的事情:

var x = document.getElementById("select");
x.addEventListener("focus", myFocusFunction, true);
x.addEventListener("blur", myBlurFunction, true);

function myFocusFunction() {
    document.getElementById("select").style.backgroundColor = "yellow"; 
}

function myBlurFunction() {
    document.getElementById("select").style.backgroundColor = ""; 
}
相关问题