我使用choo创建了一个无限滚动概念证明,bel是一个使用nanomorph和Demo修补DOM的JavaScript框架。它可以工作,但有时如果你滚动它,它似乎继续滚动直到它到达结束。您可以中断它然后它将按预期工作,直到它再次获得控制权。
主要源代码为view.js
:
module.exports = function view (state, emit) {
const rowHeight = 41
const tableHeight = 500
const startRowIndex = Math.floor(state.scrollTop / rowHeight)
const maxVisibleRows = Math.ceil(tableHeight / rowHeight) // round up
const maxRowIndex = state.contacts.length - 1
const endRowIndex = Math.min(maxRowIndex, startRowIndex + maxVisibleRows)
const remainingRows = state.contacts.length - endRowIndex
const rows = state.contacts.slice(startRowIndex, endRowIndex + 1)
const topPadding = startRowIndex * rowHeight
const bottomPadding = remainingRows * rowHeight
const onScrollDebounced = debounce(onScroll, 25)
console.log({startRowIndex, endRowIndex, topPadding, bottomPadding})
return html`
<body>
<table class="table ${prefix}" onscroll=${onScrollDebounced}>
<tbody>
${paddingRow(topPadding)}
${rows.map(tableRow)}
${paddingRow(bottomPadding)}
</tbody>
</table>
</body>
`
function onScroll (evt) {
emit('scroll', evt.target.scrollTop)
}
function paddingRow (padding) {
if (!padding) return ''
return html`
<tr style="height: ${padding}px">
<td></td>
</tr>
`
}
function tableRow (contact) {
return html`
<tr>
<td>${contact.id}</td>
<td>${contact.first_name}</td>
<td>${contact.last_name}</td>
<td>${contact.email}</td>
<td>${contact.gender}</td>
<td>${contact.ip_address}</td>
</tr>
`
}
}
您可能不需要它,但状态来自store.js
:
module.exports = function store (state, emitter) {
state.contacts = require('./data.json')
state.scrollTop = 0
emitter.on('scroll', (scrollTop) => {
state.scrollTop = scrollTop
emitter.emit('render')
})
}
这种自滚动循环是如何发生的,有没有办法阻止它?
谢谢!