更改窗口滚动上的下拉菜单 [英] Change dropdown on window scroll

查看:70
本文介绍了更改窗口滚动上的下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我更改select时,它将相应地滚动到div,并且工作正常,但是如何在文档滚动时更改select呢?

When I change select it will scroll accordingly to the div and it is working fine, But how to I change select on document scroll ?

$("select").change(function(){
  var divid = $(this).val();
  $('html, body').animate({
        scrollTop: $("." + divid).offset().top
    }, 2000);
});

div{
  height:300px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option value="div1">div1</option>
  <option value="div2">div2</option>
  <option value="div3">div3</option>
  <option value="div4">div4</option>
</select>

<div class="div1">
div1
</div>

<div  class="div2">
div2
</div>

<div  class="div3">
div3
</div>

<div class="div4">
div4
</div>

推荐答案

您可以将所有选项放入数组中,并通过窗口滚动进行检查,这样您可以拥有动态div,也可以一次检查所有这些选项.

You can put all the options into array and check it with the window scroll, this way you can have dynamic divs and also you can check them all at once.

$("select").change(function() {
  var divid = $(this).val();
  $('html, body').animate({
    scrollTop: $("." + divid).offset().top
  }, 2000);
});

var output = [];

$.each($("select option"), function(key, value) {  
  output.push(value.value);
});

$(window).on('scroll', function() {
  //checking if it is already in animation mode or not
  if (!$("html,body").is(':animated')) {
    var filtered = output.filter(a => {
      return $(this).scrollTop() >= $("." + a).position().top
    });

    //checking which options are meeting with the requirement
    if (filtered.length > 0) {   
      //selecting the last one.
      $("select").val((filtered[filtered.length - 1]))
    }
  }
});

div {
  height: 300px;
}

select {
  position: fixed;
  top: 0
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option value="div1">div1</option>
  <option value="div2">div2</option>
  <option value="div3">div3</option>
  <option value="div4">div4</option>
</select>

<div class="div1">
  div1
</div>

<div class="div2">
  div2
</div>

<div class="div3">
  div3
</div>

<div class="div4">
  div4
</div>

这篇关于更改窗口滚动上的下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆