问题
With jQuery this was always simple enough to do but am wondering how to accomplish with Vue.js. I have a sticky element on page and when that reaches a certain div id or class on scroll I want to fade it out and when scrolls back above it fade back in. I have a click event scroll currently functioning as expected on the element but am stuck on the scroll position fade in / out. div class="collapsed" is a fixed bottom element on page. When that scrolls to "fade-in-out" I would like "collapsed" to fade out and when scrolls back up past "fade-in-out" fade back in.
HTML:
<transition name="fade">
<div class="collapsed" v-show="show">
<div class="container">
<div class="row">
<div class="col-md-12">
<p>
lorem ipsum <a href="#" @click.prevent="fadeOut() + handleScrollTo('gloabl-box')"></a>
</p>
<div>
<p>Nullam sollicitudin a sapien sed</p>
<p>
Etiam ultricies elit vel sapien convallis, nec volutpat lacus imperdiet.
</p>
</div>
</div>
</div>
</div>
</div>
</transition>
OTHER DIV:
<div class="container" id="fade-in-out">
</div>
js:
export default {
name: 'app',
data() {
return {
show: true
};
},
methods: {
fadeOut: function() {
this.show = false;
}
}
};
css:
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s ease-in-out;
}
.fade-enter,
.fade-leave-active {
opacity: 0;
}
回答1:
The main concept is no difference. If you can do in jQuery so you can do the same in Vue.js.
<div id='app'>
<transition name='bottom'>
<div class='bottom' v-show='show'>
{{ lorem }}
</div>
</transition>
<div class='target' ref='target'>
<p>{{ lorem }}</p>
</div>
</div>
new Vue({
data: () => ({
show: true,
lorem: `Lorem Ipsum...`
}),
mounted() {
this.listener = () => {
let rect = this.$refs.target.getBoundingClientRect()
let top = window.innerHeight - rect.top
this.show = top < 0
}
window.addEventListener('scroll', this.listener)
/* with Intersection Observer API
this.observer = new IntersectionObserver(() => {
let rect = this.$refs.target.getBoundingClientRect()
let top = window.innerHeight - rect.top
this.show = top < 0
})
this.observer.observe(this.$refs.target)
*/
},
destroyed() {
window.removeEventListener('scroll', this.listener)
/* this.observer.unobserve(this.$refs.target) */
}
}).$mount('#app')
.bottom {
position: fixed;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
padding: 24px;
color: white;
background-color: dodgerblue;
white-space: nowrap;
text-overflow: ellipsis;
&-enter-active,
&-leave-active {
transition: opacity 0.5s ease-in-out;
}
&-enter,
&-leave-to {
opacity: 0;
}
}
.target {
padding: 24px;
color: white;
background-color: crimson;
}
JSFiddle
来源:https://stackoverflow.com/questions/59885754/fade-out-div-section-in-vue-js-when-reaching-target-section