使用Javascript来检测select元素的下拉是否可见 [英] Javascript to detect whether the dropdown of a select element is visible

查看:80
本文介绍了使用Javascript来检测select元素的下拉是否可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单中有一个select元素,并且只有在下拉列表不可见时才显示某些内容。我尝试过的事情:


  • 观察点击事件,其中奇怪的点击意味着下拉显示,甚至点击意味着下拉不显示。错过了下拉菜单可能消失的其他方式(按下转义键,切换到另一个窗口),我认为这很难正确地跨浏览器。

  • 更改事件,但只触发当选择框的值发生变化时。



想法?

这里是我最喜欢做的事情。
焦点和模糊是它的位置。


 < html> 
< head>
< title> SandBox< / title>
< / head>
< body>
< select id =ddlBox>
< option>选项1< / option>
< option>选项2< / option>
< option>选项3< / option>
< / select>
< div id =divMsg>一些文字或其他内容在这里。< / div>
< / body>
< / html>
< script type =text / javascript>
window.onload = function(){
var ddlBox = document.getElementById(ddlBox);
var divMsg = document.getElementById(divMsg);
if(ddlBox& divMsg){
ddlBox.onfocus = function(){
divMsg.style.display =none;
}
ddlBox.onblur = function(){
divMsg.style.display =;
}
divMsg.style.display =;
}
}
< / script>


I have a select element in a form, and I want to display something only if the dropdown is not visible. Things I have tried:

  • Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't. Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser.
  • Change events, but these only are triggered when the select box's value changes.

Ideas?

解决方案

here is how I would preferred to do it. focus and blur is where it is at.

<html>
    <head>
        <title>SandBox</title>
    </head>
    <body>
        <select id="ddlBox">
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
        </select>
        <div id="divMsg">some text or whatever goes here.</div>
    </body>
</html>
<script type="text/javascript">
    window.onload = function() {
        var ddlBox = document.getElementById("ddlBox");
        var divMsg = document.getElementById("divMsg");
        if (ddlBox && divMsg) {
            ddlBox.onfocus = function() {
                divMsg.style.display = "none";
            }
            ddlBox.onblur = function() {
                divMsg.style.display = "";
            }
            divMsg.style.display = "";
        }
    }
</script>

这篇关于使用Javascript来检测select元素的下拉是否可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆