我不确定如何在JavaScript中解决这个问题,所以我想了解动态变量"。如果有更好的方法,请告诉我!
给定是具有一个参数(左或右)的函数:
var footerMenuLeftOpen = true;
var footerMenuRightOpen = true;
function footerMenu(menuName, className) {
if (menuName) {
$('.content-' + className).animate({
height: "+=28px",
}, {
duration: 100
});
return false;
} else {
$('.content-' + className).animate({
height: "-=28px",
}, {
duration: 100
});
return true;
}
}
$(".content-left").click(function() {
footerMenuLeftOpen = footerMenu(footerMenuLeftOpen, 'left');
});
$(".content-right").click(function () {
footerMenuRightOpen = footerMenu(footerMenuRightOpen, 'right');
});

.content-left {
width: 200px;
height: 100px;
background-color: red;
display: inline-block;
}
.content-right {
width: 200px;
height: 100px;
background-color: blue;
display: inline-block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-left">
</div>
<div class="content-right">
</div>
&#13;
现在我想添加代码,高度(+/- 28px)的变化取决于红色或蓝色框的高度。 因此,我想在显示框时立即检查框的起始高度。
例如:
if ($('.content-left').height() > 42) {
LeftHeight: "+=28px",
} else if ($('.footer-button-box.left').height() > 28) {
LeftHeight: "+=14px",
} else {
LeftHeight: "+=5px",
}
但是我现在如何更改功能的高度值&#34; footerMenu&#34;因此,高度根据if函数的确定值而变化?
我想要像
这样的东西$('.content-' + className).animate({
height: className+Height,
}, {
duration: 100
});
...其中className将是&#34; left&#34;加上术语&#34;高度&#34 ;;所以leftHeight。
我想有一种更好的解决方案可以让它只有一个优雅的功能吗?
提前致谢!
编辑:由于我的问题很难理解,简单来说就是:
我有变数&#34; leftHeight&#34;和&#34;右高&#34;。 现在:如何从左/右是参数值的函数中访问这些变量?
目标:身高:leftHeight
想法:身高:className +&#34;身高&#34;
...那么如何使用函数参数的值作为变量名的一部分?
答案 0 :(得分:0)
我自己找到了解决方案:我不得不使用对象。
var footerMenuHeight = new Object();
if ($(".content-left").height() > 40) {
footerMenuHeight.left = 200;
} else if ($(".content-left").height() > 30) {
footerMenuHeight.left = 18;
} else {
footerMenuHeight.left = 8;
}
所以我能够使用该参数来访问该对象的值:
footerMenuHeight[className]