Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

javascript - scroll to element in horizontal div

I have a horizontal div:

horizontal div

i need to scroll to the specific element in this div via JavaScript button (after the click div must be scrolled to that element). How can I do this?

<div class="group" id="frames">
<div class="item frames-item">
<img src="1.jpg">
</div>
<div class="item frames-item">    
<img src="2.jpg">
</div>
....
....
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Or you could use the following snippet:

$('.scrollable').animate({scrollLeft: $('#dstElement').position().left}, 500);

Where position() returns the #dstElement's relative position to `.scrollable' if scrollable is positioned.

Code & Demo

    var $scroller = $('.scroller');
    // assign click handler
    $('button').on('click', function () {       
        // get the partial id of the div to scroll to
        var divIdx = $('input').val();          
        
        // retrieve the jquery ref to the div
        var scrollTo = $('#d'+divIdx)           
            // change its bg
            .css('background', '#9f3')          
            // retrieve its position relative to its parent
            .position().left;                   
        console.log(scrollTo);
        // simply update the scroll of the scroller
        // $('.scroller').scrollLeft(scrollTo); 
        // use an animation to scroll to the destination
        $scroller
          .animate({'scrollLeft': scrollTo}, 500);    
    });
    .scroller {
        width: 300px;
        height: 100px;
        overflow-x: auto;
        overflow-y: hidden;
    }
    .container {
        position: relative; /*important for the .position() method */
        height: 100px;
        width: 770px;
    }
    .container div {
        height: 90px;
        width: 60px;
        float: left;
        margin: 5px;
        background: #39f;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scroller">
        <div class="container">
            <div id="d1"></div>
            <div id="d2"></div>
            <div id="d3"></div>
            <div id="d4"></div>
            <div id="d5"></div>
            <div id="d6"></div>
            <div id="d7"></div>
           <!-- ... -->           
        </div>
    </div>
    <button>Scroll to: </button> <input type="text" value="4"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...