我正在尝试制定一个小指令,如果 div 当前滚动到底部,则将保持 div 滚动到底部,但如果用户向上滚动,则不会滚动到底部,但如果向后滚动,将继续向下滚动到底部,这是我到目前为止的代码
Vue.directive('scroller', {
bind: function(el, bindings, vnode) {
},
componentUpdated: function(el, bindings, vnode) {
console.log(el.scrollHeight - el.scrollTop, $(el).outerHeight())
if (el.scrollHeight - el.scrollTop >= $(el).outerHeight()) {
// scroll to bottom
}
// Leave the scroller alone
}
});
Run Code Online (Sandbox Code Playgroud)
这是我从控制台日志中得到的信息
bundle.js:8237 295 251.1875
bundle.js:8237 339 251.1875
bundle.js:8237 383 251.1875
bundle.js:8237 427 251.1875
bundle.js:8237 295 251.1875
Run Code Online (Sandbox Code Playgroud)
如果我一直滚动到底部,我能得到的最接近的是 295,它从
251 251.1875但一旦开始溢出并开始滚动,它似乎就停留在 295,这是我能回到的最接近的 251。
我得到了计算
AWo*_*olf -1
我认为您所拥有的增量是因为您必须将 div 容器高度纳入计算中。
另外,我还减去 50 以使重新激活点更快一些。您可以调整该值。只是用户不能完全向下滚动到末尾。
请在下面或这个小提琴中找到一个工作演示。
Vue.directive('scroller', {
bind: function(el, bindings, vnode) {
this.manualScroll = false;
},
componentUpdated: function(el, bindings, vnode) {
console.log('updated', el.scrollHeight - el.scrollTop); //$(el).outerHeight())
if (el.scrollHeight - el.scrollTop >= el.clientHeight) {
// scroll to bottom
if (!this.manualScroll) {
el.scrollTop = el.scrollHeight - el.clientHeight; // triggers scroll event
}
}
},
inserted: function(el) {
el.scrollTop = el.scrollHeight - el.clientHeight;
// console.log(el.scrollHeight)
var self = this;
el.addEventListener('scroll', function(evt) {
console.log('evt', el.scrollTop);
self.manualScroll = (el.scrollTop < el.scrollHeight - el.clientHeight - 50);
console.log('manual scroll', self.manualScroll)
})
}
});
Vue.component('DynamicUpdates', {
template: '<div class="dynamic-container" v-scroller><ul><li v-for="count in counter">{{count}}</li></ul></div>',
props: {
counter: Array
},
data: function() {
return {
updateInterval: null
};
},
computed: {
count: function() {
return this.counter.length;
}
},
mounted: function() {
this.updateInterval = setInterval(this.update, 200);
},
methods: {
update: function() {
this.counter.push(this.count++);
}
},
beforeDestroy() {
clearInterval(this.updateInterval);
}
})
new Vue({
el: '#app',
data: {
counter: [],
msg: 'hello world'
}
})Run Code Online (Sandbox Code Playgroud)
.dynamic-container {
width: 500px;
height: 150px;
overflow-y: scroll
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.js"></script>
<div id="app">
<!--{{msg}}-->
<button @click="counter=[]">
restart
</button>
<dynamic-updates :counter="counter"></dynamic-updates>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4198 次 |
| 最近记录: |