[英]Fixing Smooth Scroll Issue
我正在使用的內容的簡化版本: http : //jimmehrabbitdesigns.com/scroll.html
我可以使用滾動條,但是滾動條不會在各個部分之間切換。
例如:如果您單擊NUMBER 3,它將滾動到第三部分。 從那里開始,這就是發生的情況。
-點擊“數字2”可返回到第一部分。
-點擊“數字4”可轉到“第二部分”。
-再按一次NUMBER 3也可回到第1節。
所有部分都相同。
使用的jQuery代碼:
$('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) {
$('#right').animate({ scrollTop: target.offset().top }, 1000);
return false;
}
}
});
我對您的代碼做了一些更改。 它更簡單,可以幫助您了解正在發生的事情。 我希望它可以幫助您:
/*
1. I've changed the position fixed to position absolute on the #right element, the scroll won't work with position: fixed set
2. Added the on click event on the anchor tag this way I'm getting the href of the current clicked anchor by using $(this) and attr() method
3. Added the e.preventdefault() to prevent the default action of the anchor element
4. Doing the smooth scroll using the href got at 2 as id selector
*/
jQuery
代碼如下所示:
$('#left a').on('click', function(e) {
e.preventDefault();
var id = $(this).attr('href');
$('html, body').animate({
scrollTop: $(id).offset().top
}, 1000);
});
點擊下面的按鈕,您可以看到完整的工作片段:
$('#left a').on('click', function(e) { e.preventDefault(); var id = $(this).attr('href'); $('html, body').animate({ scrollTop: $(id).offset().top }, 1000); });
html { width: 100%; height: 100%; } body { width: 100%; height: 100%; overflow: hidden; } #left { width: 100%; height: 100%; background-color: #FFFFFF; position: fixed; top: 0; left: 0; } #right { width: 50%; height: 100%; background-color: #0000FF; position: absolute; top: 0; right: 0; z-index: 1; } #one { height: 100%; background-color: #FF0000; } #two { height: 100%; background-color: #00FF00; } #three { height: 100%; background-color: #FFFF00; } #four { height: 100%; background-color: #00FFFF; } #five { height: 100%; background-color: #FF00FF; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='container'> <div id="left"> <a href="#one">NUMBER 1</a> <br> <a href="#two">NUMBER 2</a> <br> <a href="#three">NUMBER 3</a> <br> <a href="#four">NUMBER 4</a> <br> <a href="#five">NUMBER 5</a> </div> <div id="right"> <div id="one" width="100%" height="100%">ONE</div> <div id="two" width="100%" height="100%">TWO</div> <div id="three" width="100%" height="100%">THREE</div> <div id="four" width="100%" height="100%">FOUR</div> <div id="five" width="100%" height="100%">FIVE</div> </div> </div>
您也可以根據需要檢查此JSFIDDLE 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.