根据带菜单的部分滑动页面

时间:2013-08-22 12:01:00

标签: jquery css

我正在开发一个html网站,并希望使用jquery和css创建一个函数。

我想在点击时根据侧边菜单滑动。当有人点击2号时,页面将滑动到页面上的2号块。

请查看随附的图片,以便更清楚地查看我想要做的事情!

Screenshot

2 个答案:

答案 0 :(得分:4)

DEMO: http://jsfiddle.net/gvee/LYqVk/1/

HTML

<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>

CSS

* {
    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;
}

JQuery的

$('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();

答案 1 :(得分:0)

给那个块一些像id =“blockTwo”的id。 在该号码2的侧边菜单上<a href="#blockTwo">2</a>

当您点击它时,它将转到带有该ID的块2。