水平溢出导航使项目保持在视图中

时间:2016-09-21 18:13:16

标签: jquery html css

我有一个横向溢出的导航栏,我可以用手指在手机上向左/向右滚动。我还可以向左/向右滑动主要查看区域,以更改选定的导航项目。当我这样做时,如果导航项目不在视图中,除非你滚动,否则你看不到它。

如果使用班级.active选择导航项目,是否可以将导航项目带入视图?

/* The main container */
.container .categories {
    overflow: hidden;
    overflow-x: scroll;
    white-space: nowrap;
    position: fixed;
    line-height: 20px;
    z-index: 200;
    background: #000;
    top: 50px;
    width: 100vw;
}

/* The item within the container */
.container .categories span {
    padding: 20px 15px;
    display: inline-block;
    font-weight: 300;
    border-bottom: solid 4px transparent;
    transition: border-bottom 0.2s ease-in-out;
}

/* The selected item */
.container .categories span.active {
    border-bottom: solid 4px #f47d25;
}

.container .categories span.active中有没有办法可以确保项目在活动时在视图中?

这是小提琴:https://jsfiddle.net/x9wpbkrj/5/

2 个答案:

答案 0 :(得分:0)

  

https://jsfiddle.net/x9wpbkrj/4/



body {
  color: white;
}

/* The main container */
.container .categories {
  /*overflow: hidden;*/
  /*overflow-x: scroll;*/
  /*white-space: nowrap;*/
  /*position: fixed;*/
  line-height: 20px;
  z-index: 200;
  background: #000;
  top: 50px;
  width: 100vw;

  /*display: inline-block;*/
}


/* The item within the container */
.container .categories span {
  padding: 20px 15px;
  display: inline-block;
  font-weight: 300;
  border-bottom: solid 4px transparent;
  transition: border-bottom 0.2s ease-in-out;
}


/* The selected item */
.container .categories span.active {
  border-bottom: solid 4px #f47d25;
}

<div class="container">
	<div class="categories">
		<span>Trending</span>
		<span>New & Updated</span>
		<span>Discover</span>
		<span>Most Played</span>
		<span>Staff Picks</span>
		<span>New & Updated</span>
		<span>Discover</span>
		<span>Most Played</span>
		<span>Staff Picks</span>
		<span>New & Updated</span>
		<span>Discover</span>
		<span class="active">Most Played</span>
		<span>Staff Picks</span>
	</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

看起来scrollIntoView可能是我正在寻找的答案:

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

修改

上述方法有效,但如果某个项目部分在视图中,则不会滚动。如果我使用scrollLeft,它似乎工作得很好。

$('.container .categories')[0].scrollLeft = 
$(`.container .categories > span:nth-child(${offset + 1})`)[0].offsetLeft;