【发布时间】:2014-06-25 23:36:59
【问题描述】:
我正在尝试创建一个滑动侧边栏,并且想知道是否有比我已经在做的更好的方法。
<img id = "MenuIcon" src = "MenuIcon.png" alt = "Menu Icon" onclick = "slideSideBar()" />
目前我只是检查sideSlideCount是否是偶数-如果是侧边栏一定不能出来,所以当函数被调用时它会滑出;如果 sideSlideCount 是奇数(即 % 2 != 0),则侧边栏应该滑出视图。
var sideSlideCount = 0; // variable used with the side bar
var bodyHeight = $(window).height();
var bodyWidth = $(window).width();
console.log(bodyWidth);
function slideSideBar() {
if (sideSlideCount % 2 == 0) { // if sideSlideCount is even, i.e. the side bar is hidden
$("#SideBar").animate({width: bodyWidth / 6}, 600); // slide the bar out to 300 width, 0.6 seconds
$("#SideLinks").fadeTo(1000, 0.8); // fade the links into view, 1 second, to 100% opacity
}
else { // else, if the side bar is in view
$("#SideBar").fadeIn(300).animate({width: 0}, 600); // slide the bar back out of view (0 width), 0.6 seconds
$("#SideLinks").fadeTo(200, 0); // fade the links out of view, 0.2 seconds, to 0% opacity
}
sideSlideCount++; // increment the variable
}
【问题讨论】:
-
代替
if (sideSlideCount%2 == 0),您可以交换块并使用if (sideSlideCount%2)。您也可以使用if (sideSlideCount)和之后的sideSlideCount = ++sideSlideCount%2甚至sideSlideCount = !sideSlideCount。 -
@RobG 我想我在这里感兴趣的是一种避免全局变量 sideSlideCount; 的方法。假设侧边栏有一个新闻部分,当您单击该部分时,它应该显示更多选项 - 这还需要一个全局变量来跟踪它是否打开。看起来我最终会得到大量的全局变量,我不希望这样做。我可以只使用布尔值,但即使这样也必须是布尔值。
-
@connor0728 什么时候真正开始滑动?什么叫
slideSideBar? -
@plalx 我有一个典型的 3 栏菜单图标,当单击它时,侧边栏会滑入/滑出。我现在已将代码包含在原始帖子中。
标签: javascript jquery