Javascript在keydown上切换 [英] Javascript Toggle on keydown

查看:90
本文介绍了Javascript在keydown上切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在谈到JS功能时,我是新手。我之前使用过的所有内容,我都倾向于按原样使用,但我一直在尝试组合和修改一个函数,以便在特定按键上切换(高度和不透明度)Div。我有第一部分(可以在'ctrl + o'组合中显示div),但不能根据当前显示状态将它与if语句结合显示或隐藏。

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.

当前工作'仅显示'JS:

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

不工作'打开/关闭'JS(我试过改变这个地方;这更像是为了让我知道我想要实现的目标):

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!

推荐答案

您想要显示和隐藏元素,为什么要设置其高度和可见性?只需使用切换即可显示/隐藏它。

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();
    }
});

查看您的代码

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

    }
});

这篇关于Javascript在keydown上切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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