平滑滚动直接调用div

时间:2014-04-23 10:58:16

标签: jquery wordpress twitter-bootstrap-3

我正在使用此脚本制作一个带有smootscroll的单页网站

$('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 - 125
    }, 1000);
    return false;
  }
}
});

但是如果我直接使用div调用div?page_id = 6#apps它会忽略

target.offset().top - 125 

ik如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用onhashchange事件查看它是否符合您的需求:

$(function () {
    $('a[href*=#]:not([href=#])').click(scrollToElement);
});

$(window).one('hashchange', scrollToElement).on('load', function () {
    $(this).triggerHandler('hashchange');
});

function scrollToElement() {
    var hash = this.hash ? this.hash : window.location.hash;
    var $target = $(hash).length ? $(hash) : $('[name=' + hash.slice(1) + ']');
    if ($target.length) {
        $('html,body').animate({
            scrollTop: $target.offset().top - 125
        }, 1000);
        return false;
    }
}