Javascript Toggle on keydown

2020-04-23 06:43发布

问题:

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 function to get a Div to toggle (height & opacity) on a specific keypress. I have the first part (can get the div to show on a 'ctrl + o' combo), but can't combine it with an if statement to show or hide, based on current display status.

Current working 'show only' JS:

$(document).keydown(function (e) {
    if (e.keyCode == 79 && e.ctrlKey) {
        document.getElementById('thediv').style.height = 'auto';
        document.getElementById('thediv').style.opacity = '1';
        return false;
    }
});

Not working 'toggle on/off' JS (I've tried changing this all over the place; this is more to give an idea of what I'm trying to achieve):

$(document).keydown(function (e) {
    if (e.keyCode == 76 && e.ctrlKey) {

        function toggler('thediv') {
            var myDiv = document.getElementById('thediv').style.height;
            if (myDiv == "auto") {
                document.getElementById('thediv').style.height = "0px";
                document.getElementById('thediv').style.opacity = "0";

            } else {
                document.getElementById('thediv').style.height = "auto";
                document.getElementById('thediv').style.height = "1";
            }
        }

    }
});

Any help would be really appreciated!

回答1:

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";
            }
        }

    }
});