【问题标题】:Jquery Smooth Scroll Using Offset.topJquery 使用 Offset.top 平滑滚动
【发布时间】:2017-10-20 13:04:39
【问题描述】:

我正在尝试创建从topNav 到网页上各个部分的平滑滚动效果。在下面的代码中,我重新创建了我遇到的问题,这只是我似乎无法让滚动过程动画化。我的链接跳转到正确的部分,并且我一直 console.logged 以确保在 'click' 时抓取了正确的元素,但它仍然无法正常工作。

有人可以帮忙吗?最初我认为这可能与以下事实有关,即我没有给出navlinks 个人ID,而是将它们与类名分组。这可能是我的问题的一部分吗?

$(document).ready(function() {
	
	$('.slide').click(function() {
		
		var link = $(this).attr('href');
		
		$('html,body').animate({
			scrollTop: $(link).offset().top}, 1000);
		return false;
		
		
		
		
	});
	
	
	
});
* {
	padding: 0;
	margin: 0;
}

nav {
	width: 100%;
	height: 120px;
}

div {
	width: 100%;
	height: 500px;
}
<nav>
	<a href="#first" class="slide">Section 1</a>
	<a href="#second" class="slide">Section 2</a>
	<a href="#third" class="slide">Section 3</a>
	<a href="#fourth" class="slide">Section 4</a>
</nav>

<div>
	<a name="first">Section 1</a>
</div>

<div>
	<a name="second">Section 2</a>
</div>

<div>
	<a name="third">Section 3</a> 
</div>

<div>
	<a name="fourth">Section 4</a>
</div>

【问题讨论】:

    标签: javascript jquery html css smooth-scrolling


    【解决方案1】:

    首先,您是否在项目中加载了 JQuery?

    如果是这样,您在 HTML 中犯了一个小错误。 Href 属性引用的是 ID,而不是名称属性!

    我的解决方案:

    $(document).ready(function() {
    	
    	$('.slide').click(function() {
    		
    		var link = $(this).attr('href');
    		
    		$('html, body').animate({
    			scrollTop: $(link).offset().top}, 1000);
    		return false;	
    	});
    });
    * {
    	padding: 0;
    	margin: 0;
    }
    
    nav {
    	width: 100%;
    	height: 120px;
    }
    
    div {
    	width: 100%;
    	height: 500px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <nav>
    	<a href="#first" class="slide">Section 1</a>
    	<a href="#second" class="slide">Section 2</a>
    	<a href="#third" class="slide">Section 3</a>
    	<a href="#fourth" class="slide">Section 4</a>
    </nav>
    
    <div id="first">
    	<a>Section 1</a>
    </div>
    
    <div id="second">
    	<a>Section 2</a>
    </div>
    
    <div id="third">
    	<a>Section 3</a> 
    </div>
    
    <div id="four">
    	<a>Section 4</a>
    </div>

    【讨论】:

    • 我确实已经加载了它。啊!非常感谢您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多