简体   繁体   English

Javascript-页面加载后滚动到元素

[英]Javascript - scroll to element after the page has loaded

I have a subpage with sections and sidebar with links to each section on every page. 我有一个带有部分的子页面和带有每个页面上每个部分链接的侧边栏。 I am scrolling to each of them like so: 我像这样滚动到每个人:

function scrollToElement(element) {
  if($(element) && $(element).offset()) {

    $('html,body').animate({
      scrollTop: $(element).offset().top - 80
    });
  }
}

$('.anchor-links').click(function() {
  var element = $(this).attr('id').split('-');

  if (element[0] == 'download') {
    $("html, body").animate({
      scrollTop: 0
    });
  } else {
    scrollToElement('#' + element[0]);
  }
});

This are the links in the sidebar on each page: 这是每个页面侧栏中的链接:

<div class="slideout-menu">
  <ul>
    <li>
      <a href="/subpage#download" class="anchor-links" id="download-link">Last ned</a>
    </li>
    <li>
      <a href="/subpage#about" class="anchor-links" id="about-link">Om oss</a>
    </li>
    <li>
      <a href="/subpage#faq" class="anchor-links" id="faq-link">Spørsmål og svar</a>
    </li>
    <li>
      <a href="/subpage#contact" class="anchor-links" id="contact-link">Kontakt</a>
    </li>
    <li>
      <a href="/all">Se alle magasiner</a>
    </li>
  </ul>
</div>

And this is my subpage: 这是我的子页面:

<div class="background-container show-for-medium" id="download">
  <img src="/uploads/{{ $subpage->cover }}" alt="" />
</div>

@section('topBar')
  @include('customer.layouts.partials.top-bar')
@show

<div class="panel">
  @section('alexBox')
    @include('customer.layouts.partials.alex-box')
  @show

  @section('availability')
    @include('customer.layouts.partials.availability-info')
  @show
</div>
<section class="row faq">
  <div class="small-12 medium-10">
    <div class="subpage-section" id="about">
      {!! $subpage->about !!}
    </div>
    <div class="subpage-section" id="faq">
      {!! $subpage->faq !!}
    </div>
    <div class="subpage-section" id="contact">
      {!! $subpage->contact !!}
    </div>
  </div>
</section>

Since, the navbar has a height of 80px , I have set it up in the script to scroll to the navbar on navigating to each section other than download which is the top most section. 由于navbarheight80px ,因此我已在脚本中将其设置为navbar到导航navbar (导航至除下载部分(最顶部的部分)以外的其他部分)上。 When I am navigating to a section from another page on small screens, it doesn't scroll all the way to the bottom of navbar, so I can see the content of the above section. 当我在小屏幕上从另一个页面导航到某个部分时,它不会一直滚动到导航栏的底部,因此我可以看到上述部分的内容。 This happens only on small screens and only on navigating to some section from another page, if I am on the same page or navigating from another page on the big screen, then it works fine. 这仅在小屏幕上发生,并且仅在从另一页导航到某个部分时发生,如果我在同一页面上,或者从大屏幕的另一页导航,则工作正常。 When I do console.log($(element).offset().top); 当我做console.log($(element).offset().top); I get different values for when I navigate to section from another page, then it is: 当我从另一个页面导航到部分时,得到的值是不同的,那就是:

983.46875

And when I am on the subpage already, then it is: 当我已经在子页面上时,它是:

1151.46875

this is where I am logging that: 这是我记录的地方:

function scrollToElement(element) {
  if($(element) && $(element).offset()) {
    console.log($(element).offset().top);
    $('html,body').animate({
      scrollTop: $(element).offset().top - 80
    });
  }
}

Since, I am dynamically creating and hiding some elements on the subpage I think the wrong offset comes from that, because I guess it gets the offset before all the elements are created. 因为,我正在动态创建和隐藏子页面上的某些元素,所以我认为错误的偏移量是由此产生的,因为我猜想它会在创建所有元素之前获得偏移量。 This is the script that does that: 这是执行此操作的脚本:

//switch app and google store buttons
function shopButtons () {
  if (navigator.userAgent.match(/Android/i)) {
    $('.js-store-link').attr('href', 'https://play.google.com/store/apps/details?id=myapp.areader');
    $('.js-store-img').attr('src', '/img/google-store.svg');
  }

  if (navigator.userAgent.match(/iPhone|iPod/i)) {
    $('.js-store-link').attr('href', 'https://itunes.apple.com/no/app/myapp+/id777109367?mt=8');
    $('.js-store-img').attr('src', '/img/app-store.svg');
  }

}

$(document).ready(function(){
shopButtons();

  $.ajax({
    url: 'https://apiEndpoint/13/salesposter.json' ,
    data : { search: 'test' },
    dataType: 'json',

    success : function(json) {
      var partner = json.partner;
      var posterName = json.name;
      $('#posterName').text(posterName);
      var metaArray = json.metadata;
      $('.meta3').attr('href', metaArray[0].value);
      $('.spid-login').attr('href', 'https://payment.schibsted.no/flow/login/');

      metaArray.forEach(function(item, index, array){
        $('.meta'+item.prio).html(item.value);
      });
    }
  });

  //hide store buttons in alex box on subpages
  if (window.location.pathname.includes('/subpage')) {
    var element = $('#' + window.location.hash.substr(1));
    scrollToElement(element);
    $('.js-alex-box-store-buttons').hide();
  }
});

But not sure how to fix that? 但是不确定如何解决该问题吗? I have tried with wrapping the call to scrollElement() from this script with the window.onload function, so that it executes after the page is completely loaded, but that didn't help, function wasn't called at all then. 我尝试用window.onload函数包装从此脚本对scrollElement()的调用,以便在页面完全加载后执行该脚本,但这无济于事,此后根本没有调用该函数。 I have also tried by placing the whole function inside the success method of the ajax call, but then it scrolls all the way to the top. 我也尝试过将整个函数放在ajax调用的success方法中,但是然后一直滚动到顶部。

As mentioned in your comments, that you need javascript for the fixed navbar. 如评论中所述,您需要使用JavaScript来固定导航栏。 You need to wait until the element is defined . 您需要等待直到element is definedelement is defined Otherwise you will get his null-pointer-exception . 否则,您将获得他的null-pointer-exception So you only can execute the scrollToElement() in the document.ready function or later. 因此,您只能在document.ready函数或更高版本中执行scrollToElement()

metaArray.forEach(function(item, index, array) {     
    $('.meta'+item.prio).html(item.value); 
});

is asynchronous. 是异步的。 I think that your .meta-elements have no height at document.ready , when you scroll to your element with scrollToElement(...) . 我认为当您使用scrollToElement(...)滚动到元素时, .meta-elementsdocument.ready处没有高度。 Try to add the function into your success: function. 尝试将函数添加到success:函数中。

Example for jQuery: jQuery的示例:

 var isSubpage = window.location.pathname.indexOf("subpage") >= 0; $(document).ready(function() { var element = window.location.hash; scrollToElement(element); $('.anchor-links').click(function(event) { if(isSubpage){ event.preventDefault() var element = $(this).attr('id').split('-'); if (element[0] == 'download') { $("html, body").animate({ scrollTop: 0 }); } else { scrollToElement('#' + element[0]); } } }); }); function scrollToElement(element) { if($(element) && $(element).offset()) $('html,body').animate({ scrollTop: $(element).offset().top - 80 }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="slideout-menu"> <ul> <li> <a href="/subpage#download" class="anchor-links" id="download-link">Last ned</a> </li> <li> <a href="/subpage#about" class="anchor-links" id="about-link">Om oss</a> </li> <li> <a href="/subpage#faq" class="anchor-links" id="faq-link">Spørsmål og svar</a> </li> <li> <a href="/subpage#contact" class="anchor-links" id="contact-link">Kontakt</a> </li> <li> <a href="/all">Se alle magasiner</a> </li> </ul> </div> 

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

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