Якорь на доп страницах ведущий на главную, как анимацию сохранить?

Здравствуйте.

Помогите доработать якорь, мне человек делал, но не все доделали, хочу сделать полноценный якорь, с главной страницы он работает все ок, блоки они на главной страницы, блоки якоря, когда кликаем по ссылкам, перенаправляет к блоку плавно и есть анимация, когда я нахожусь на доп странице где нет блоков якорей но есть только ссылки и при клике на ссылку, нас перекидывает на главную страницу где якорь блоки и спускает к нужному блоку, точнее перекидывает, нет анимации, плавного спуска, как можно передать плавный спуск, в скрипте пытались передать через строку урла.

якорь ссылки
<li><a href="https://сайт.ru/#kkk" data-href="#kkk" title="" class="scroll">Как оформить</a></li>

<b>блок ссылки якоря</b>
<div id="kkk">Как оформить</div>


js
<script>
      var w_hash = window.location.hash;
      if (w_hash) {
        setTimeout(function() {
          window.scrollTo(0, 0);
        }, 1);
      } 
      $('html, body').stop().animate({
        scrollTop: $(w_hash).offset().top
      }, 777);
      $(document).ready(function () {
        $("a.scroll").on("click", function (e) {
          var anchor = $(this);
          $('html, body').stop().animate({
            scrollTop: $(anchor.data('href')).offset().top
          }, 777);
          return false;
        });
      });
    </script>
  • Вопрос задан
  • 177 просмотров
Решения вопроса 1
ws17
@ws17 Автор вопроса
Вот решение рабочее, тестил и на мобиле и в хроме и в мозиле, весь инет обыскал так и не нашел решения, но за бабосы мне сделали )))

Делюсь бесплатно:

<script>
      jQuery('a[href*="#"]')
      // Remove links that don't actually link to anything
        .not('[href="#"]')
        .not('[href="#0"]')
        .on('click', function(event) {
        event.preventDefault();
        // On-page links
        var _this = jQuery(this), id = _this.attr('href').substring(_this.attr('href').indexOf('#'));

        if(jQuery(id).length > 0) {

          // Figure out element to scroll to
          var target = jQuery(this.hash);
          target = target.length ? target : jQuery('[name=' + this.hash.slice(1) + ']');

          // Does a scroll target exist?
          if (target.length) {
            // Only prevent default if animation is actually gonna happen
            event.preventDefault();
            jQuery('html, body').animate({
              scrollTop: target.offset().top
            }, 1000, function() {

            });
          }

        } else {
          window.location.href = _this.attr('href');
        }

      });

      var target = window.location.hash;

      // delete hash so the page won't scroll to it
      window.location.hash = "";

      // now whenever you are ready do whatever you want
      // (in this case I use jQuery to scroll to the tag after the page has loaded)
      $(window).on('load', function() {
        if (jQuery(target).length) {
          $('html, body').animate({
            scrollTop: jQuery(target).offset().top
          }, 700, 'swing', function () {});
        }
      });


      jQuery(function(){

        if(jQuery(target).length > 0) {

          jQuery('html, body').animate({
            scrollTop: jQuery(target).offset().top
          }, 1000, function() {
            history.pushState(null,null, target);
          });
        }

        return false;
      });
    </script>
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы