如何将列表的活动元素滚动到视图中?

时间:2016-04-24 14:49:14

标签: jquery css

基本上我喜欢让活动元素始终可见。

此示例中的活动元素具有类option todo

如果用jQuery点击按钮scrolltoactive,怎么办呢?

谢谢你,

亚历

body {
   font-family: Helvetica, Arial, Sans-Serif;
}

ul.variant-scroll{
  position: relative;
  width: 100%;
  height: 55px;
  padding: 0 0 0 20px;
  display: block;
  float: left;
  list-style: none;
  counter-reset: section;
  white-space: nowrap;
  overflow: hidden;
  overflow-x: scroll;
}

ul.variant-scroll li{
  display: inline-block;
  background: #f2f2f2;
  color: #6056c3;
  padding: 0 25px;
  height: 55px;
  line-height: 55px;
  font-size: 1.142em;
  cursor: pointer;
  pointer-events: auto;
  margin: 0 -4px 0 0 !important;
}

ul.variant-scroll li.todo{
  background: #6056c3;
  color: #fff;
  cursor: default;
  pointer-events: none;
}

ul.variant-scroll li.todo a{
  color: #fff;
}

ul.variant-scroll li.notdone.todo,
ul.variant-scroll li.checkout{
  background: #f2f2f2;
  color: #525252 !important;
  cursor: default;
  pointer-events: none;
}

ul.variant-scroll li.notdone.todo a,
ul.variant-scroll li.checkout a{
  color: #525252 !important;
}

ul.variant-scroll li::before {
  counter-increment: section;
  content: counter(section) ". ";
}
<button type="button" class="scrolltoactive">Scroll to active</button>

<ul class="variant-scroll">
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>  
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>     
</ul>

1 个答案:

答案 0 :(得分:3)

这是一个有效的fiddle

您可以使用属性scrollLeft()

像这样:$('.variant-scroll').scrollLeft($('.todo').offset().left)

修改

如果您希望它在点击按钮后工作,只需在按钮中添加一个事件监听器:

$('.scrolltoactive').on('click',function(){
    $('.variant-scroll').scrollLeft($('.todo').offset().left);
});