如何在滚动时选择 div?
How can I get selected div on scroll?
我有一个 div 包含许多高度随机的单元格。
目的是:"the user stop the scroll to choose a cell, all cells can be chosen"。
一个单元格被左上角的光标 selected/chosen。
当用户滚动 div 时单元格的光标变化。
我做了一个演示,但问题是当用户在底部时,无法通过光标选择最后 N 个单元格。
请问我该怎么做?
感谢您的帮助:)
$(document).ready(function() {
for (i = 0; i < 100; i++) {
var h = Math.floor(Math.random() * (50 + 1) + 20);
$('.content').append('<div id="' + i + '" class="cell" style="height:' + h + 'px;"></div>');
}
$(document).on('scroll', function() {
var id = current();
$('.cursor').css('top', $('#' + id).position().top + 'px')
});
});
function current() {
$('.cell').each(function() {
if ($(this).position().top > $(document).scrollTop()) {
id = $(this).attr('id');
return false;
}
});
return id;
}
.cell {
width: 100px;
border: 1px solid;
margin-bottom: 5px;
}
.cursor {
width: 0px;
height: 0px;
z-index: 9999;
position: absolute;
border-style: solid;
border-width: 10px 10px 0px 0px;
border-color: #000 transparent transparent transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
<div class="cursor"></div>
</div>
这是因为你的事件是基于滚动的,当滚动结束时它无法决定将光标放在哪个元素上所以只需在你的代码中添加以下 css 以增加 space 在内容的底部继续滚动到最后一个元素。
.content {
margin-bottom : 130px;
}
或者把最后一个参数设为65
var h = Math.floor(Math.random() * (50 + 1) + 65);
注意:至少需要65才能到最后一个。
我有一个 div 包含许多高度随机的单元格。 目的是:"the user stop the scroll to choose a cell, all cells can be chosen"。 一个单元格被左上角的光标 selected/chosen。 当用户滚动 div 时单元格的光标变化。 我做了一个演示,但问题是当用户在底部时,无法通过光标选择最后 N 个单元格。 请问我该怎么做?
感谢您的帮助:)
$(document).ready(function() {
for (i = 0; i < 100; i++) {
var h = Math.floor(Math.random() * (50 + 1) + 20);
$('.content').append('<div id="' + i + '" class="cell" style="height:' + h + 'px;"></div>');
}
$(document).on('scroll', function() {
var id = current();
$('.cursor').css('top', $('#' + id).position().top + 'px')
});
});
function current() {
$('.cell').each(function() {
if ($(this).position().top > $(document).scrollTop()) {
id = $(this).attr('id');
return false;
}
});
return id;
}
.cell {
width: 100px;
border: 1px solid;
margin-bottom: 5px;
}
.cursor {
width: 0px;
height: 0px;
z-index: 9999;
position: absolute;
border-style: solid;
border-width: 10px 10px 0px 0px;
border-color: #000 transparent transparent transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
<div class="cursor"></div>
</div>
这是因为你的事件是基于滚动的,当滚动结束时它无法决定将光标放在哪个元素上所以只需在你的代码中添加以下 css 以增加 space 在内容的底部继续滚动到最后一个元素。
.content {
margin-bottom : 130px;
}
或者把最后一个参数设为65
var h = Math.floor(Math.random() * (50 + 1) + 65);
注意:至少需要65才能到最后一个。