繁体   English   中英

使用javascript将元素正确滚动到页面顶部

[英]properly scroll element to the top of the page using javascript

我想做的是,如果URL包含特定单词,则将具有特定元素的页面呈现到页面顶部。 我已经可以使用以下命令成功提取URL:

  if(window.location.href.indexOf("Awesome") > -1) {
    alert('hey, your url has Awesome in it!')
  };

但是,在使页面与特定元素滚动到顶部进行渲染方面,我正处于十字路口……有什么建议吗?

更新 -这是我当前的逻辑:

window.addEventListener('load', function(){

  (function(){

    function goto(id) {
      var elem = document.getElementById(id);
      window.scrollTo(0, elem.getBoundingClientRect().top);
    }

    if(window.location.href.indexOf("Awesome") > -1) {
      goto('full--stop');
    };
  })();

如何获取元素的位置并在那里滚动?

 function goto(id) { var elem = document.getElementById(id); window.scrollTo(0, elem.getBoundingClientRect().top); } goto('three'); 
 <button onclick="goto('two')">Go to two</button> <button onclick="goto('three')">Go to three</button> <div id="one">One</div> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <div id="two">Two</div> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <div id="three">Three</div> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> 

更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect


另外,如果您不想用JavaScript进行操作,则浏览器具有内置功能,可滚动到ID与浏览器URL中的#匹配的元素。 因此, example.com/page#myid / myid将滚动到id为myid的元素。

您可以通过两种方式执行此操作:

第一种方法:

$('html, body').animate({
    scrollTop: $("#your element ID").offset().top
}, 2000);

第二种方法:

<div id="myDiv"></div>

location.href = "#";
location.href = "#myDiv";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM