【问题标题】:Slide Page according to section with menu根据带菜单的部分滑动页面
【发布时间】:2013-08-22 21:05:37
【问题描述】:

我正在开发一个 html 网站,并想使用 jquery 和 css 制作一个函数。

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

请查看所附图片以更清楚地了解我想要做什么!

Screenshot

【问题讨论】:

标签: jquery css


【解决方案1】:

演示: 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();

【讨论】:

  • 谢谢,太棒了
  • 如果我想添加背景以显示当前在屏幕上查看的块。
【解决方案2】:

给该块一些 id,例如 id="blockTwo"。 在那个数字 2 的侧边菜单中输入&lt;a href="#blockTwo"&gt;2&lt;/a&gt;

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

【讨论】:

    猜你喜欢
    • 2012-05-26
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多