如何计算水平滚动位置

时间:2013-12-18 10:44:19

标签: javascript jquery scroll horizontalscrollview

我制作了一个水平滚动网站。主要问题是我无法在第一次加载或刷新时突出显示活动菜单项。

我也无法将主动链接永久保留在家中。因为如果用户在其他页面上活动时刷新页面,主页将突出显示。 我的网站与此类似:something like this website

2 个答案:

答案 0 :(得分:1)

如果你正在使用jQuery,你可以使用.scrollLeft()获取页面的水平滚动,以像素为单位。

像这样:

$(window).scroll(function() {
    var scroll = $('html, body').scrollLeft();
    // do stuff with the value...
});

答案 1 :(得分:0)

检查一下...... http://jsfiddle.net/aGCVt/2/

你也可以使用document.getElementById('container')。scrollLeft =你的页面宽度;

<强> HTML

<button onclick="gotoPage(0)">First</button>
    <button onclick="gotoPage(1)">Second</button>
    <button onclick="gotoPage(2)">Third</button>
    <div style="white-space: nowrap; overflow: auto; width: 500px;height: 300px;" id="container">
        <div id="firstPage" class="common"></div>
        <div id="secondPage" class="common"></div>
        <div id="thirdPage" class="common"></div>
    </div>

<强> CSS

.common {
    width: 500px;
    height: 300px;
    display: inline-block;
}

#firstPage {

    background-color: red;
}

#secondPage {
    background-color: yellow;
}

#thirdPage {
    background-color: green;
}

<强> JAVASCRIPT

function gotoPage(pageNo) {
    var scroll = 500 * pageNo;
    document.getElementById('container').scrollLeft = scroll;
}

你也可以使用jquery $('#container')。scrollLeft()。