【发布时间】:2016-02-16 15:31:03
【问题描述】:
我想将点击的列表元素居中(例如,如果我点击最左边的元素,那么它会移动到中间,替换当前的中间元素)。
所以我认为也许切换当前“活动”和点击元素的索引可能值得一试。我无法更改元素的索引值。
最好的解决方案是更改每个列表元素的索引,以便它们保持某种逻辑顺序并将点击的元素居中。
我是 JS 的初学者,所以我知道可能有更好的方法,所以我愿意接受建议。 ;)
所以,我正在考虑两个解决方案:
它用点击的元素替换它的位置。例如:
1 - 2 - 3 - 4 - 5
3 is middle and I click 5
The new order : 1 - 2 - 5 - 4 - 3
它移动列表的每个元素。例如:
1 - 2 - 3 - 4 - 5
3 is middle and I click 5
The new order : 3 - 4 - 5 - 1 - 2
这里是codepen:http://codepen.io/anon/pen/wMOZVd
function horizontalSlider() {
var sliderElement = $('.horizontal-slider ul li');
var active = $('.horizontal-slider .active');
var activeIndex = active.index();
var center = Math.floor(sliderElement.length / 4);
sliderElement.click(function() {
var thisElement = $(this).index();
var newActive = $('.horizontal-slider .active');
var newActiveIndex = newActive.index();
if (thisElement == newActiveIndex) {
$(this).addClass('active').children().addClass('active-sub');
} else {
$(this).addClass('active').children().addClass('active-sub');
newActive.removeClass('active').children().removeClass('active-sub');
}
});
}
horizontalSlider();
.horizontal-slider {
text-align: center;
width: 100%;
margin: 0 auto;
}
.horizontal-slider ul {
display: inline-block;
text-transform: uppercase;
font-size: 2rem;
width: 100%;
}
.horizontal-slider ul li {
padding: 3%;
cursor: pointer;
}
.horizontal-slider ul ul {
display: none;
}
.active {
transition: all .5s ease;
font-weight: 900;
position: relative;
transform: scale(1.25);
}
.active-sub {
top: 70%;
left: 1%;
display: block !important;
position: absolute;
}
.active-sub li {
text-transform: none;
font-size: 0.9rem;
font-weight: 500;
}
li {
list-style: none;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="horizontal-slider relative">
<ul>
<li>Mar 16
<ul>
<li>Lorem ips</li>
</ul>
</li>
<li>Apr 04
<ul>
<li>Lorem ips</li>
</ul>
</li>
<li>May 22
<ul>
<li>Lorem ips</li>
</ul>
</li>
<li class="active">Jun 30
<ul class="active-sub">
<li>Lorem ips</li>
</ul>
</li>
<li>Jul 12
<ul>
<li>Lorem ips</li>
</ul>
</li>
<li>Aug 15
<ul>
<li>Lorem ips</li>
</ul>
</li>
<li>Sep 03
<ul>
<li>Lorem ips</li>
</ul>
</li>
</ul>
</div>
【问题讨论】:
-
请参阅"Should questions include “tags” in their titles?",其中的共识是“不,他们不应该”!
-
by
center the clicked on你的意思是它应该在中间吗?踢最左边怎么样,这应该在中间,左边没有其他 el 吗?请澄清 -
@johnSmith - 是的,它应该在中间。如果我点击最左边的那个,那么它会移动到中间,替换当前的中间元素。
-
中间呢?他要去哪里?
-
@MoshFeu 所以我在考虑两种解决方案。 1. 它用点击的元素替换它的位置。例如:1 - 2 - 3 - 4 - 5 3 在中间,我点击 5 新顺序:1 - 2 - 5 - 4 - 3 2. 它移动列表中的每个元素。例如:1 - 2 - 3 - 4 - 5 3 在中间,我点击 5 新顺序:3 - 4 - 5 - 1 - 2
标签: javascript jquery html css frontend