我在屏幕上有两个部分,左侧有菜单项,右侧有内容。内容div是固定位置,具有自动滚动功能。
左侧菜单有3个项目,点击任意项目,我希望用户导航到内容div上的特定部分(已修复)。
我的代码
function goToByScroll(id) {
// Scroll
$('.content-pos-fixed').animate({
scrollTop: $("#" + id).offset().top - 152
},'slow');
}
由于某种原因它没有按预期工作。
答案 0 :(得分:1)
试用此代码
function goToByScroll(id,event) {
event.preventDefault();
$('.content-pos-fixed').animate({
scrollTop: $(id).offset().top+$('.content-pos-fixed').scrollTop()
},'slow');
}
$(document).ready(function(){
$('a').on('click',function(event){
var id=$(this).attr('href');
goToByScroll(id,event);
});
function goToByScroll(id,event) {
event.preventDefault();
$('.content-pos-fixed').animate({
scrollTop: $(id).offset().top+$('.content-pos-fixed').scrollTop() },'slow');
}
});

* { margin: 0; padding: 0; box-sizing: border-box; font-family: arial; text-decoration: none; color: black; }
nav { position: fixed; top: 0; left: 0; right: 0; background: #fff; z-index: 9999; }
nav a { color: white; display: inline-block; padding: 1rem; float: left; font-weight: bold; }
section { height: 100vh; }
nav a:nth-child( 3n + 1), main section:nth-child( 3n + 1) { background: #B1A464; }
nav a:nth-child( 3n + 2), main section:nth-child( 3n + 2) { background: #2d74b2; }
nav a:nth-child( 3n + 3), main section:nth-child( 3n + 3) { background: #e5ec10; }
nav a:nth-child( 3n + 4), main section:nth-child( 3n + 4) { background: #cfa5df; }
div { position: relative; padding: 1rem; }
footer { background: rgba(255, 255, 255, 0.4); height: 55px; position: fixed; bottom: 0; left: 0; right: 0; z-index: 7777; }
.down { background: white; display: block; border-radius: 100px; width: 50px; height: 50px; position: fixed; bottom: 5%; right: 5%; z-index: 8888; }
.down::after { content: "▼"; position: relative; left: 15px; top: 15px; }
nav a {
color: white;
display: inline-block;
padding: 1rem;
float: left;
font-weight: bold;
width: 100%;
}
nav {
position: fixed;
/* top: 0; */
left: 0;
right: 0;
background: #fff;
z-index: 9999;
width: 300px;
height: 100%;
}
main {
float: right;
width: calc(100% - 300px);
overflow: auto;
position: fixed;
right: 0;
height: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<nav data-scroll-header>
<a data-scroll href="#Home">Home</a>
<a data-scroll href="#About">About</a>
<a data-scroll href="#Services">Services</a>
<a data-scroll href="#Contact">Contact</a>
</nav>
<main class="content-pos-fixed">
<section id="Home">
<div>
<h1>Home</h1>
</div>
</section>
<section id="About">
<div>
<h1>About</h1>
</div>
</section>
<section id="Services">
<div>
<h1>Services</h1>
</div>
</section>
<section id="Contact">
<div>
<h1>Contact</h1>
</div>
</section>
</main>
<footer>
<a data-scroll href="#About" class="down"></a>
</footer>
&#13;