我使用PHP创建了一个列表,其中包含从level-1到level-X的动态数量的li项和类。根据级别将列表项缩进。随着这个列表变得越来越长,当较少缩进(缩进为层次)的项目离开视口时,访问者可能会丢失上下文。
为了防止这种刺激,我开始修复缩进较少的元素,使其留在视口中,直到它的同级元素通过滚动来取代它的位置。
但这只适用于第一级缩进,但我尝试以相同的方式处理以下缩进项,对它们进行分组,并始终在视口中显示它们的上下文(层次结构)。
就是这样一个简单的列表。表示缩进的级别:
<ul>
<li class="level level-1">1</li>
<li class="level level-2">1.1</li>
<li class="level level-2">1.2</li>
<li class="level level-2">1.3</li>
<li class="level level-1">2</li>
<li class="level level-2">2.1</li>
<li class="level level-2">2.1.1</li>
</ul>我在jsfiddle上发布了一个级别的示例。
也许有谁可能有一个想法?
亲切的问候
发布于 2014-05-20 22:54:32
如果你能够在你的PHP中添加一个数据,你也可以添加一个level-x属性来给我们提供深度。这只会让我们更容易进行一些比较,而不必在以后进行字符串操作。
在本例中,我在级别x上进行了快速搜索和替换,以便将数据属性快速添加到标记中,但是您可以从PHP>添加这两个属性,这意味着您可以忽略演示代码的housework部分。
然后,您将使用以下命令执行以下操作:
Javascript:
$(document).ready(function () {
// Just some housework to add in the correct CSS again
$('li').each(function (index, el) {
$(el).addClass('level-' + $(el).data('depth'));
});
//// end of housework
allEls = $('.testList li');
elOffsets = [];
// Get and cache all the offsets of all li elements
$.map(allEls, function (el, i) {
elOffsets[i] = $(el).offset().top;
});
var clone = null;
$(window).scroll(function () {
//remove clone if there is one present
if (clone) {
clone.remove();
clone = null;
}
var offScreenElIndex = null; // Initialize an index for the first element to be offScreen
var scrollDistance = $(document).scrollTop() + 20; // add the fixed height of the clone 20px from css.
$.each(elOffsets, function (i, elOffset) {
// See if the elements position is offscreen (negative) according to latest scrollDistance
if (elOffset - scrollDistance < 0) {
offScreenElIndex = i; // Set that as the offScreenElIndex
} else if (elOffset - scrollDistance >= 0 && offScreenElIndex !== null && clone === null) {
// Else we are now at the next element in the list which is "onScreen" after the "offScreen" el and there hasn't been a clone made yet
//create a clone
el = $('.testList li').get(offScreenElIndex); // get the list element to clone (the previous one to this "i" as it is "offScreen")
if ($(el).data('depth') > 1) {
// if the depth of this is bigger than one, make the "cloned" element the previous depth
el = $(el).prevAll('[data-depth="' + ($(el).data('depth') - 1) + '"]').get(0);
}
createClone(el);
} else {
// if no exit to stop the foreach and wait for the next scroll event.
return false;
}
});
});
function createClone(el) {
clone = $('<div/>')
.addClass($(el).attr('class'))
.addClass('clone fixed')
.text($(el).text());
$('.testList').prepend(clone);
}
});工作演示:http://jsfiddle.net/3BDA3/1/
https://stackoverflow.com/questions/23757104
复制相似问题