horizontal scroll inside container

可紊 提交于 2019-12-01 18:04:48

As @Script47 mentioned, you'll want to apply overflow-x as a CSS property to your element, in addition the width (to act as a viewport). Here's what your final CSS might look like:

.container {
    white-space: nowrap;
    overflow-x: scroll;
    width: 250px;
    position: relative;
}

After that, you'll need to modify your JS slightly. You'll still want to scroll to the offset of the element, but you'll also need to take into account your current scroll position.

(To clarify, if you clicked orange - which has an offset initially of 250px, post-animation, the offset for orange would be0px, and black would be250px. If you then click black, it will attempt to scroll to 250px, which is the orange element.)

Here's what the updated JS might look like:

jQuery(document).ready(function ($) {

    $(".scroll").click(function (event) {
        var current = $('.container').scrollLeft();
        var left = $(this.hash).position().left;        

        event.preventDefault();

        $('.container').animate({
            scrollLeft: current + left
        }, 200);
    });
});

A fiddle to demonstrate: https://jsfiddle.net/bpxkdb86/4/

For the fiddle, I removed physical white-space in the HTML (to prevent the divs from having space between them) using <!-- comments -->, and also added position: relative to the containing element (to use position)

A CSS solution, try adding this to you element in CSS,

overflow-x: scroll;

This, should do it for you.

You need two changes for this to work.

First, add height and width for the container and then set overflow in css.

width:250px;
height:250px;
overflow: auto;

Second update jquery to animate the container, now it is animating the body.

$('.single-box').animate({

JSFiddle is avaialble in the following link

https://jsfiddle.net/jym7q0Lu/

just use a css if you want your div to be scrollable..

   .container {
       white-space: nowrap;
       overflow-x: scroll;
       width: 250px;
       position: relative;
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!