Javascript to detect whether the dropdown of a select element is visible

后端 未结 7 1001
甜味超标
甜味超标 2020-12-19 08:39

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
相关标签:
7条回答
  • 2020-12-19 09:12

    This rudimentary example demonstrates how to do it with setInterval. It checks once every second for the display state of your select menu, and then hides or shows a piece of content. It works according to the description of your problem, and no matter what hides the select menu, it will display that piece of content accordingly. In other words, the toggleDisplay() was setup just to demonstrate that.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
    <title></title>
    <script language="javascript" type="text/javascript">
    
    var STECHZ = {
        init : function() {
            STECHZ.setDisplayedInterval();
        },
        setDisplayedInterval : function() {
            STECHZ.isDisplayedInterval = window.setInterval(function(){
                if ( document.getElementById( "mySelectMenu" ).style.display == "none" ) {
                    document.getElementById( "myObjectToShow" ).style.display = "block";
                } else {
                    document.getElementById( "myObjectToShow" ).style.display = "none";
                }
            }, 1000);
        },
        isDisplayedInterval : null,
        toggleDisplay : function() {
            var mySelectMenu = document.getElementById( "mySelectMenu" );
            if ( mySelectMenu.style.display == "none" ) {
                mySelectMenu.style.display = "block";
            } else {
                mySelectMenu.style.display = "none";
            }
        }
    };
    
    window.onload = function(){
    
        STECHZ.init();
    
    }
    
    </script>
    </head>
    <body>
        <p>
            <a href="#" onclick="STECHZ.toggleDisplay();return false;">Click to toggle display.</a>
        </p>
        <select id="mySelectMenu">
            <option>Option 1</option>
            <option>Option 2</option>
            <option>Option 3</option>
        </select>
        <div id="myObjectToShow" style="display: none;">Only show when mySelectMenu is not showing.</div>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题