0

我正在使用 jQuery 和片段标识符来创建状态更改,具体取决于用户当前正在查看的单页站点的哪个部分。

我终于让它工作了,但由于 Safari 和 Chrome 都不会显示片段标识符,我无法将它变成一个变量,因此系统崩溃了。

有没有办法专门针对 WebKit 浏览器强制执行此操作或以其他方式访问片段?

编辑:在下面添加代码

(function($){
$.fn.sectionMove = function() {

    return this.each(function() {          
    $(this).click(function() {
            if(window.location.hash){
                  var $hash = window.location.hash;
            } else if (!window.location.hash) {
                  var $hash = '#section1';
            }
            $n = $hash.substring($hash.length-1,$hash.length);

            $("div#headerNav ul li:nth-child(" + $n + ") a").removeClass('on');

            var $anchor = $(this);
            $('html, body').stop().animate({
                scrollTop: $($anchor.attr('href')).offset().top
            }, 1000,'easeInOutExpo', function(){
                var $hash = window.location.hash;
                $n = $hash.substring($hash.length-1,$hash.length);
                $("div#headerNav ul li:nth-child(" + $n + ") a").addClass('on');
            });
            event.preventDefault(); 
        });
     });

   };
})(jQuery);
4

1 回答 1

1

我已经设法自己解决了。问题出在我的 jquery 的以下几行:

$('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top

虽然这确实允许在页面上进行平滑滚动,但它导航到锚点而不使用片段标识符更新 url。

如果有人对如何完成同样的事情感兴趣,那么下面的代码应该会有所帮助。我根据自己的需要对其进行了修改,但必须归功于 Arial Flesler (http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links)

function filterPath(a) {
        return a.replace(/^\//, '').replace(/(index|default).[a-zA-Z]{3,4}$/, '').replace(/\/$/, '')
    }

    var e = filterPath(location.pathname);
    var f = scrollableElement('html', 'body');
    $('a[href*=#]').each(function () {
        var b = filterPath(this.pathname) || e;
        if (e == b && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/, '')) {
            /*var anchor1 = window.location.hash; */
            var c = $(this.hash),
                target = this.hash;
            if (target) {
                var d = c.offset().top;
                $(this).click(function (a) {        

                    a.preventDefault();
                    $(f).animate({
                        scrollTop: d
                    }, 1000,'easeInOutExpo', function () {
                        location.hash = target
                        $("div#headerNav ul li a").removeClass('on');

                        $n = target.substring(target.length-1,target.length);
                        $("div#headerNav ul li:nth-child(" + $n + ") a").addClass('on');

                    })
                })
            }
        }
    });
于 2010-10-29T21:32:25.687 回答