Scrolling down after a few seconds to an anchor

你说的曾经没有我的故事 提交于 2021-02-19 07:40:06

问题


I wonder if it's possible to scroll down after 6 seconds to an anchor?

I found this script where it scrolls down a couple of pixels but it's not completely what I'm looking for.

<script type='text/javascript'>
     setTimeout("window.scrollBy(0,270);",6000);
</script>

Also how can i make it scroll down smoothly? I found this but how do i combine it with the other script?

function scrollToAnchor(aid) {
     var aTag = $("a[name='" + aid + "']");
     $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

$("#link").click(function() {
     scrollToAnchor('id3');
});

I'm not very familiar with JS so I would really appreciate some help :)

the site I'm working is: kip.mascomm.be

UPDATE:

I got the first part to work, thanks to Seth, but can someone please give me a code to make the performance smooth:

var delay = 1000 * 10;
    setTimeout(function() {
        location.hash = "#kippenkramen";
    }, delay);

回答1:


Time Delay example:

var delay=1000 * 6;//1*6 seconds
setTimeout(function(){
  //window.scrollTo(500, 0);//scrolls to specific location
  //location.hash = "#elmentid"; //scrolls to element with given id
},delay); 

(How to set time delay in javascript)

Animated Scrolling function:

function scrollTo(element, to, duration) {
  if (duration < 0) return;
  var difference = to - element.scrollTop;
  var perTick = difference / duration * 10;

  setTimeout(function() {
    element.scrollTop = element.scrollTop + perTick;
    if (element.scrollTop == to) return;
    scrollTo(element, to, duration - 10);
  }, 10);
}

(Cross browser JavaScript (not jQuery...) scroll to top animation)




回答2:


  document.querySelectorAll('a[href]').forEach( el => {
    el.onclick = (e) => {
      e.preventDefault()
      setTimeout(() => {
        window.location = el.getAttribute('href')
      }, 6000);
    }
  })


来源:https://stackoverflow.com/questions/29775133/scrolling-down-after-a-few-seconds-to-an-anchor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!