11

Basically I have a website with horizontally scrolling content. As in the whole page scrolls horizontally, not just a div.

I am trying to implement left and right arrow buttons that onmousedown or hover (it doesn't matter too much which one yet), scrolls the whole window (smoothly) left and right.

This website does pretty much what I want with the little centred arrows: http://www.clholloway.co.za

Can anyone help with this? Cheers.

4

3 回答 3

18

我认为用一点 jQuery 你可以实现你正在寻找的东西。基本思想是处理一些事件(onmouseenter、mousedown 等),然后您可以使用这些事件来启动滚动。

想象你有一些看起来像这样的标记:

<div id="parent">
    <div class="contentBlock">1</div>
    <div class="contentBlock">2</div>
    <div class="contentBlock">3</div>
    <div class="contentBlock">4</div>
    <div class="contentBlock">5</div>
</div>
<span id="panLeft" class="panner" data-scroll-modifier='-1'>Left</span>

<span id="panRight" class="panner" data-scroll-modifier='1'>Right</span>

还有一些样式可以确保它会导致窗口滚动:

#parent {
    width:6000px;
}
.contentBlock {
    font-size:10em;
    text-align:center;
    line-height:400px;
    height:400px;
    width:500px;
    margin:10px;
    border:1px solid black;
    float:left;
}
.panner {
    border:1px solid black;
    display:block;
    position:fixed;
    width:50px;
    height:50px;
    top:45%;
}
.active{
    color:red;
}
#panLeft {
    left:0px;
}
#panRight {
    right:0px;
}

您可以结合使用样式、setInterval 和 jQuery.scrollLeft() 来实现您想要的效果。

(function () {

    var scrollHandle = 0,
        scrollStep = 5,
        parent = $(window);

    //Start the scrolling process
    $(".panner").on("mouseenter", function () {
        var data = $(this).data('scrollModifier'),
            direction = parseInt(data, 10);        

        $(this).addClass('active');

        startScrolling(direction, scrollStep);
    });

    //Kill the scrolling
    $(".panner").on("mouseleave", function () {
        stopScrolling();
        $(this).removeClass('active');
    });

    //Actual handling of the scrolling
    function startScrolling(modifier, step) {
        if (scrollHandle === 0) {
            scrollHandle = setInterval(function () {
                var newOffset = parent.scrollLeft() + (scrollStep * modifier);

                parent.scrollLeft(newOffset);
            }, 10);
        }
    }

    function stopScrolling() {
        clearInterval(scrollHandle);
        scrollHandle = 0;
    }

}());

完整的 jsFiddle 演示了这种方法:http: //jsfiddle.net/jwcarroll/atAHh/

于 2013-08-06T18:58:22.510 回答
2

我已经创建了这个Fiddle来帮助你。看看它是否有助于为您指明正确的方向。您可能需要根据您的情况对其进行调整,但希望它能够满足您的需求。

请注意,我设置overflow:hidden<body>不显示的显式滚动条;如果需要,请更改。

干杯!

于 2013-08-06T19:05:24.293 回答
0

如果您将body元素设置为大于视口的宽度(并且不设置溢出隐藏),浏览器将自动支持水平箭头键滚动。这与在此网页上使用垂直箭头滚动相同。

于 2013-08-06T17:56:16.367 回答