Scroll horizontally starting from right to left wi

2019-02-11 17:51发布

问题:

So I am wondering if there is a possibility to have a different starting position with the overflow:scroll value;

When you start scrolling in a div the default behavior is to scroll form left to right:

|<--Scrollbar-Starting-Left-->_________________________________________________|

would it possible that it starts at the right?

|_________________________________________________<--Scrollbar-Starting-Right-->|

In my example the red and green items are first visible, I'd like the green and blue item to be visible first :)

I've tried direction:rtl; but no luck

回答1:

You can of course use direction:rtl

document.querySelector('input').addEventListener('input', function(){
  document.querySelector('.box').scrollLeft = this.value;
})
.box{
  width: 320px;
  height: 100px;
  border:1px solid red;
  overflow: scroll;
  direction: rtl;  /* <-- the trick */
}

.box::before{ content:''; display:block; width:400%; height:1px; }
<div class='box'></div>
<br>
<input placeholder='scrollLeft value'>

FiddleDemo

This may be useful using direction http://css-tricks.com/almanac/properties/d/direction/



回答2:

I don't Know about any solution with just CSS but you can use Jquery to change the initial position of the scrollbar like this:

$(document).ready(function(){
    $('#box').scrollLeft($(this).height())
})

Check this Demo Fiddle



回答3:

With javascript you can just set scrollLeft property when page gets loaded (using el.scrollLeft = el.scrollWidth - el.clientWidth;).



回答4:

There is an unexpected behavior if you add closing parenthesis at the end of text for the top answer. (Tested in Chrome 54)

<div id="box">
    <div id="inner_box">
        <div class="item" style="background:red;"></div>
        <div class="item" style="background:green;"></div>
        <div class="item" style="background:blue;">te(st)</div>
    </div>
</div>

Watch this feedle for result : http://jsfiddle.net/mm37pqxa/



回答5:

You can do this with one line of jQuery:

$("#box").scrollLeft(480);



回答6:

I've been working in a project and for me works very well like this:

overflow-x: scroll;   
overflow-y: hidden;   
white-space: nowrap;