当从其他页面单击时,锚链接的scrollTop偏移量不起作用

时间:2016-05-30 03:54:35

标签: javascript jquery anchor

我的网站上有一个固定位置的标题,当用户向下滚动时,它会粘在屏幕顶部。该网站的导航包括两个锚点链接,向下滚动到主页上的相应部分,然后一个链接指向不同的页面(博客)。这是我用于平滑滚动锚链接的代码:

$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top - $('header').height()
        }, 600);
        return false;
      }
    }
  });
});

主页上的一切都很棒。我遇到的问题是当您在博客页面上点击主页的两个锚链接之一时。从技术上来说它应该放在主页上,除非它没有像你已经在主页上那样通过标题的高度来抵消位置

我对javascript一点都不好。我在网上找到了这个代码(并获得了一些关于本网站偏移量的帮助)。我真的很努力,但它还没有点击。为什么会发生这种情况?我该如何解决?

1 个答案:

答案 0 :(得分:0)

您的问题是您拥有的代码仅适用于点击事件。 因此,当您在网址中加载带有锚点的页面时,不会触发滚动到事件。

您需要一些仅在页面加载时触发的代码。

 <script>
  $(function() {
    $('.editor')
      .froalaeditor({
        // Set the image upload parameter.
        imageUploadParam: 'image',
        // 1. I'M GUESSING THIS IS THE PARAM PASSED

        // Set the image upload URL.
        imageUploadURL: <%= attach_guide_post_image_path =%>,
        // 2. MADE THIS PATH IN THE ROUTES


        // Set request type.
        imageUploadMethod: 'POST',

        // Set max image size to 5MB.
        imageMaxSize: 5 * 1024 * 1024,

        // Allow to upload PNG and JPG.
        imageAllowedTypes: ['jpeg', 'jpg', 'png', 'gif']
      })
      .on('froalaEditor.image.beforeUpload', function (e, editor, images) {
        // Return false if you want to stop the image upload.

        //3. SO I PUT ERROR MESSAGE IN THESE?? IF SO SHOULD IT BE A POPUP OR TEXT ON THE SCREEN AND HOW
      })
      .on('froalaEditor.image.uploaded', function (e, editor, response) {
        // Image was uploaded to the server.
      })
      .on('froalaEditor.image.inserted', function (e, editor, $img, response) {
        // Image was inserted in the editor.
      })
      .on('froalaEditor.image.replaced', function (e, editor, $img, response) {
        // Image was replaced in the editor.
      })
      .on('froalaEditor.image.error', function (e, editor, error, response) {
        // Bad link.
        else if (error.code == 1) { ... }

        // No link in upload response.
        else if (error.code == 2) { ... }

        // Error during image upload.
        else if (error.code == 3) { ... }

        // Parsing response failed.
        else if (error.code == 4) { ... }

        // Image too text-large.
        else if (error.code == 5) { ... }

        // Invalid image type.
        else if (error.code == 6) { ... }

        // Image can be uploaded only to same domain in IE 8 and IE 9.
        else if (error.code == 7) { ... }

        // Response contains the original server response to the request if available.
      });
  });
</script>