如何水平滚动div放在右边?

问题描述 投票:0回答:1

我从stackoverflow中的一个问题中提取了以下代码。当滚动到绿色框时,绿色框将显示为主Div的左侧。我可以搬到绿色的盒子里,那么它会出现在主要Div的右侧吗?

http://jsfiddle.net/o8ngaq0e/

我尝试了以下功能,但没有奏效:

var $scroller = $('.scroller');
$('button').on('click', function () {       
  var divIdx = $('input').val();          
  var scrollTo = $('#d'+divIdx)     
    .css('background', '#9f3')          
    .position().right;                   
  console.log(scrollTo);
  $scroller.animate({'scrollLeft': scrollTo}, 500);    
});

.position().right;只做着色部分。它没有滚动到框中。我怎样才能做到这一点?

jquery html css
1个回答
0
投票

我想这就是你想要的。我在JS代码中记录了计算。

注意:这仅适用于容器中不可见的元素。所以你不能把第一个元素放在容器的右边。

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;
  /*
    To position the element at the right side of the container
    subtract the width of the container and add the width
    of the element. Including the margin.
  */
  scrollTo = scrollTo - 300 + 70;
  // 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" />
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.