Javascript Toggle on keydown

后端 未结 1 462
盖世英雄少女心
盖世英雄少女心 2021-01-24 01:22

I\'m pretty new when it comes to getting my head around JS functions. Everything I\'ve used before, I\'ve tended to use as-is, but I\'ve been trying to combine and modify a func

相关标签:
1条回答
  • 2021-01-24 01:43

    You want to show and hide an element, why set its height and visibility? Just show/hide it with toggle.

    $(document).keydown(function (e) {
        if (e.keyCode == 76 && e.ctrlKey) {
             $("#thediv").toggle();
        }
    });
    

    Looking at your code

    $(document).keydown(function (e) {
        if (e.keyCode == 76 && e.ctrlKey) {
    
            //This funciton is never called, you define it, do not call it!
            function toggler('thediv') { //<-- Error Here, you have a string as an argument?
                var myDiv = document.getElementById('thediv').style.height;
                if (myDiv == "auto") {
                    document.getElementById('thediv').style.height = "0px";  //<--Bad practice using document.getElementById('thediv') over and over. Store it into a variable and reference it.
                    document.getElementById('thediv').style.opacity = "0";
    
                } else {
                    document.getElementById('thediv').style.height = "auto";
                    document.getElementById('thediv').style.height = "1";
                }
            }
    
        }
    });
    
    0 讨论(0)
提交回复
热议问题