Javascript的滚动效果会干扰链接

Javascript - scroll effect interferes with links

本文关键字:干扰 链接 滚动 Javascript      更新时间:2023-09-26

$('body a').click(function(e){
		e.preventDefault();
		var goTo = $(this).attr('href').replace('#','');
		$("html, body").animate({
			scrollTop:$('a[name="'+goTo+'"]').offset().top
		},1100);
		
		window.location.hash = "#"+goTo;
		
	});

这是我的javascript代码,它工作得很好,除了当我试图点击链接时,我会得到这个错误:

类型错误:$(…(.偏移量(…(未定义

这是因为e.preventDefault((;它阻止链接工作,并且您将其设置为主体中的所有标签

尝试使用另一个脚本

try:

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