在谈到JS功能时,我是新手。我之前使用过的所有内容,我都倾向于按原样使用,但我一直在尝试组合和修改一个函数,以便在特定按键上切换(高度和不透明度)Div。我有第一部分(可以在'ctrl + o'组合中显示div),但不能根据当前显示状态将它与if语句结合显示或隐藏。
目前工作'仅显示'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(我已经尝试过改变这一点;这更像是为了让我知道我想要实现的目标):
$(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";
}
}
}
});
任何帮助都会非常感激!
答案 0 :(得分:1)
您想要显示和隐藏元素,为什么要设置其高度和可见性?只需使用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";
}
}
}
});