if 和 elseif 语句都会触发

Both if and elseif statements triggering

本文关键字:语句 elseif if      更新时间:2023-09-26

我正在构建一个按钮,该按钮远离鼠标并"环绕"窗口。对jQuery/JavaScript来说相对较新,我把它作为一个学习练习(我的灵感来自这个页面上的#4:http://panjiva.com/jobs/challenges)。

背景:这实际上是我的第二次尝试,可能不是解决问题的最优雅的解决方案。基本上,在第二个版本中,有隐藏的"临时"按钮,它们与按钮一起移动,并在按钮开始离开屏幕时出现。(我的第一次尝试只有两个按钮,但我在那里遇到了问题。

下面是一个嵌套的 if/else 语句,用于检测按钮的一部分何时移出窗口,如果是,则在正确位置显示一个临时按钮以提供"换行"效果。它还检查整个按钮是否已移出屏幕,如果是,则将按钮移动到新坐标(临时按钮已公开的位置)。

我认为整个 if/else 语句应该只允许按钮换行到一侧,即使按钮留在角落。 但是,当离开角落时,它有时会包裹到 2 或 3 个角。为什么会这样?

我已经创建了一个包含完整代码的 JSFiddle:http://jsfiddle.net/aaronmacy/AVwpU/

所有的帮助/建议将不胜感激!

// Is any part of the button about to move off the page?
// To the top?
if (edgeTop < 0) {
    // Always wrap to the bottom
    bottom.show();
    // Is the button disappearing?
    if (edgeBottom < 0) {
        // Move the button
        buttonNextY += parseInt(viewportHeight);
        moveAll();
        // Hide everything else
        hideTemps();
    }
    else {
        moveAll();
    }
}
// To the right?
else if (edgeRight > parseInt(viewportWidth)) {
    // Wrap to the left
    left.show();
    // Is the button disappearing?
    if (edgeLeft > parseInt(viewportWidth)) {
        buttonNextX -= parseInt(viewportWidth);
        moveAll();
        hideTemps();
    }
    else {
        moveAll();
    }
}
// To the bottom?
else if (edgeBottom > parseInt(viewportHeight)) {
    // Wrap to the top
    top.show();
    // Is the button disappearing?
    if (edgeTop > parseInt(viewportHeight)) {
        buttonNextY -= parseInt(viewportHeight);
        moveAll();
        hideTemps();
    }
    else {
        moveAll();
    }
}
// To the left?
else if (edgeLeft < 0) {
    // Wrap to the right
    right.show();
    // Is the button disappearing?
    if (edgeRight < 0) {
        buttonNextX += parseInt(viewportWidth);
        moveAll();
        hideTemps();
    }
    else {
        moveAll();
    }
}
// If the button is completely inside the window
else {
    moveAll();
}

我认为他们的要求不清楚"屏幕的另一边"......我会说你的脚本工作正常。他们并没有真正考虑奖金要求,他们只是添加它,看看哪个候选人会付出更多的努力......无论如何,在按钮之间增加距离,至少在 x 上添加按钮宽度,在 y 轴上添加按钮高度......并且不要隐藏任何副本。它会自然包裹,相信我;)