【问题标题】:How to smooth scroll two elements at the same time using scrollIntoView()?如何使用 scrollIntoView() 同时平滑滚动两个元素?
【发布时间】:2019-04-07 18:23:12
【问题描述】:

我正在尝试使用 scrollIntoView() 同时平滑滚动两个 div。这两种方式我都试过了,但只有最后一个div叫scrolls:

尝试1:有两个参数的函数:只有第二个参数滚动

function precedent_scroll(link, section) {
  document.getElementById(link).scrollIntoView({behavior: "smooth"});
  document.getElementById(section).scrollIntoView({behavior: "smooth"});
}

尝试2:背靠背调用函数:只有“section2_IDname”滚动

function precedent_scroll(section) {
  document.getElementById(section).scrollIntoView({behavior: "smooth"});
}

$("#id").click(function() {precedent_scroll("section1_IDname"), precedent_scroll("section2_IDname")});

仅使用 scrollIntoView() 可以吗?

【问题讨论】:

  • 如果目标是滚动到一个,则需要一个 setTimeout,让用户在特定时间看到它,然后滚动到其他
  • @charlietfl 这就是我目前用作替代解决方案的方法,但是有没有办法同时使用 scrollIntoView({behavior: "smooth"}) (或类似的东西)动画)?
  • 未内置...没有。可以使用带有 delay() 的 jQuery 动画,但它需要你自己的位置计算

标签: javascript jquery html scroll smooth-scrolling


【解决方案1】:

让它与 jQuery 一起工作:

function double_scroll(id1, id2) {
  var id1_parent_st = $([id1 parent]).scrollTop();
  var id2_parent_st = $([id2 parent]).scrollTop();
  $([id1 parent]).animate({
    scrollTop: $(id1).position().top + id1_parent_st
  }, 500, function(){
  });
  $([id2 parent]).animate({
    scrollTop: $(id2).position().top + id2_parent_st
  }, 500, function(){
  });
}

$([div]).click(function() {double_scroll("#p1_link", "#p1_section")});

【讨论】:

  • 你知道如何在没有 Jquery 的情况下做到这一点吗?
  • @NahushFarkande 我敢肯定,如果您只是查看如何将部分代码转换为纯 JS,它会起作用。例如,stackoverflow.com/questions/15521081/…
猜你喜欢
  • 2019-06-18
  • 2019-02-21
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 2017-02-14
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多