【发布时间】:2013-08-22 21:05:37
【问题描述】:
我正在开发一个 html 网站,并想使用 jquery 和 css 制作一个函数。
我想在点击时根据侧边菜单滑动。当有人点击 2 号时,页面会滑到页面上的 2 号块。
请查看所附图片以更清楚地了解我想要做什么!
【问题讨论】:
-
一个jsfiddle会很好,你能提供一些代码吗,看看这个以前的堆栈A/Q stackoverflow.com/questions/5666844/…
我正在开发一个 html 网站,并想使用 jquery 和 css 制作一个函数。
我想在点击时根据侧边菜单滑动。当有人点击 2 号时,页面会滑到页面上的 2 号块。
请查看所附图片以更清楚地了解我想要做什么!
【问题讨论】:
演示: http://jsfiddle.net/gvee/LYqVk/1/
<div id="content">
<div class="section" id="section1">section 1 content</div>
<div class="section" id="section2">section 2 content</div>
<div class="section" id="section3">section 3 content</div>
</div>
<ul id="menu">
<li> <a href="#section1">Section 1</a>
</li>
<li> <a href="#section2">Section 2</a>
</li>
<li> <a href="#section3">Section 3</a>
</li>
</ul>
* {
margin: 0;
border: 0;
padding:0;
}
#menu {
position: fixed;
list-style-type: none;
right: 10px;
top: 20%;
width: 100px;
}
#menu .highlighted {
background-color: yellow;
}
#content {
margin-right: 120px;
}
#section1 {
background-color: red;
height: 400px;
}
#section2 {
background-color: blue;
height: 200px;
}
#section3 {
background-color: green;
height: 800px;
}
$('a[href*=#]').click(function (e) {
e.preventDefault();
var id = $(this).attr('href');
var scrollTo = $(id).offset().top;
$('html,body').animate({
'scrollTop': scrollTo
}, 500);
});
$(document).scroll(function () {
highlightSection();
});
function highlightSection() {
// Where's the scroll at?
var currentPosition = $(this).scrollTop();
// Remove highlights from all
$('a[href*=#]').removeClass('highlighted');
// Loop over each section
$('#content .section').each(function () {
// Calculate the start and end position of the section
var sectionStart = $(this).offset().top;
var sectionEnd = sectionStart + $(this).height();
// If the current scroll lies between the start and the end of this section
if (currentPosition >= sectionStart && currentPosition < sectionEnd) {
// Highlight the corresponding anchors
$('a[href=#' + $(this).attr('id') + ']').addClass('highlighted');
}
});
};
// Call on page load too!
highlightSection();
【讨论】:
给该块一些 id,例如 id="blockTwo"。
在那个数字 2 的侧边菜单中输入<a href="#blockTwo">2</a>
当您单击它时,它将转到具有该 ID 的块 2。
【讨论】: