switch 语句滚动值 (Javascript)

switch statement scroll value (Javascript)

我正在尝试创建一个网站,该网站会根据用户向下滚动页面的距离触发不同的事件。

到目前为止,我一直在使用的逻辑是通过一系列 if 语句来检查用户在页面下方的位置:

window.onscroll = function(ev) {

if(window.innerHeight + window.scrollY >= <insert value or reference here>) 
{
     <enter code here>
}
...

我认为将其写成 switch 语句会更方便:

switch(window.innerHeight + window.scrollY)
{
    case (<insert value or reference here>):
        <enter code here>
        break;
        ...
}

但出于某种原因,它作为 if 语句而不是 switch 语句触发。谁能帮我理解为什么?我也想知道是否有更有效的方法来做到这一点,或者也欢迎任何建议。

谢谢!

$("#block1").hover(
  function() {
    $("#loc").text("mouse scrolled to block 1");
  }, function() {
    $("#loc").text("");
  }
);


$("#block2").hover(
  function() {
    $("#loc").text("mouse scrolled to block 2");
  }, function() {
    $("#loc").text("");
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="loc" style=" position: fixed;
    bottom: 0;
    right: 0;
    width: 300px;background-color:green;text-align:center ">xxx</div>
<div style="height:500px; background-color:grey">this is long content. it requires you to scroll to see it all</div>
<div id="block1" style="height:  250px; background-color:pink;">this is a block of comment. you got here by entering the block</div>
<div id="block2" style="height:  350px; background-color:yellow;">this is a block of comment. you got here by entering the block</div>

I would also like to know if there's a more efficient way of doing this or any suggestions are also welcome.

我建议将内容放在 DIV 中,然后使用 jQuery,基于此触发 mouseover/mouseout 事件。

它不会起作用,因为您在 if 语句中比较 >=,而 switch==。如果你想要一个 switch 语句,它应该像下面这样:

switch(true){
  case (window.innerHeight + window.scrollY >= <insert value or reference here>) :
      ....
      break;
}

表达式的计算结果应始终为真或假。