更改窗口滚动上的下拉菜单

时间:2018-12-28 10:39:59

标签: javascript jquery html

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

$("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>

3 个答案:

答案 0 :(得分:3)

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

$("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>

答案 1 :(得分:1)

select进入视口时,您可以使用Intersection Observer API来更改div

更新:已经提供了一个很好的有效答案来解决该问题,我只是出于教育目的,为对Intersection Observer和{{3 }}。

请注意,并非所有浏览器都完全支持提供的示例,并且不应在生产环境中使用该示例(当前代码段已使用Chrome 71进行了测试):

var dropdown = document.querySelector('#dropdown');

var targets = document.querySelectorAll('.target');

var options = {
  root: document.querySelector('#scrollable'),
  rootMargin: '0px',
  threshold: 0
}

var callback = function(entries, observer) { 
  entries.forEach(entry => {
  // If the element enters the viewport...
    if (entry.isIntersecting) {
      // ... then update the dropdown.
      dropdown.value = entry.target.id;
    }
  });
};

var observer = new IntersectionObserver(callback, options);

targets.forEach(target => observer.observe(target));

dropdown.addEventListener('change', () => {
  var element = document.getElementById(dropdown.value);
  element.scrollIntoView(true);
});
#scrollable {
  border: 1px solid #ccc;
  height: 150px;
  overflow: auto;
  width: 300px
}
<select id="dropdown">
  <option value="div1">div1</option>
  <option value="div2">div2</option>
  <option value="div3">div3</option>
  <option value="div4">div4</option>
</select>

<div id="scrollable">
  <div class="target" id="div1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc et dolor a leo semper suscipit. Donec quis lobortis mauris, quis finibus neque. Integer justo mi, faucibus vel fermentum at, convallis eget dui. Quisque pharetra velit in lacus ornare, a blandit tortor tempus. Nulla sit amet sapien turpis. Morbi ut dapibus lacus, id tristique ligula. Phasellus vel neque vitae metus congue vulputate. Cras laoreet euismod nisl sed aliquet. Maecenas eu facilisis magna. Etiam et tempor justo, vel dictum sem.</div>
  <div class="target" id="div2">Pellentesque gravida, massa ac venenatis volutpat, erat neque ornare risus, convallis dignissim ante erat a felis. Suspendisse erat ligula, egestas non ante eu, iaculis aliquam ante. Aliquam vestibulum mattis erat, sed convallis quam rutrum fringilla. Nulla hendrerit libero sed nibh faucibus, nec pharetra felis tempor. Vestibulum in sem augue.</div>
  <div class="target" id="div3">Suspendisse potenti. Nullam blandit dapibus eros, sed semper quam eleifend in. Nunc elementum ligula eget volutpat imperdiet. Sed cursus rhoncus semper. Pellentesque dignissim nibh a facilisis viverra. Sed eu dictum quam. Suspendisse consectetur libero orci, quis ornare metus tincidunt eget. Fusce congue lectus ligula, non aliquet urna ullamcorper non. Aliquam leo ipsum, scelerisque ut tortor sodales, vestibulum aliquet mauris. Pellentesque sit amet sapien pulvinar diam malesuada euismod in at sapien. Mauris eleifend laoreet nibh vitae interdum. Suspendisse eget velit a tortor egestas fermentum. Nunc in libero felis.</div>
  <div class="target" id="div4">Integer rhoncus fringilla viverra. Vivamus tempor mi quis laoreet porta. In maximus tincidunt tincidunt. In viverra a est dictum vulputate. Curabitur eu sagittis odio, sed molestie massa. Donec ac neque vel mauris pellentesque blandit id non nisl. Curabitur egestas, enim semper viverra aliquam, nunc orci pretium diam, egestas dictum elit purus eu nisl. Cras aliquet dignissim fringilla. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean id viverra tellus, sit amet gravida orci. Aliquam elementum posuere augue.</div>
</div>

答案 2 :(得分:0)

即使我建议使用插件来避免任何不一致之处,下面也会显示一个快速解决方案。它提取焦点div的索引,并更改选择下拉列表的值。但是,此解决方案仅限于焦点事件。

 $('div[value^="div"]').on('focus',function(e){
        let selectedIndex = $(this).prop('class').match(/\d+/g)[0] - 1;
        $('select').prop('selectedIndex', selectedIndex);
});