Tailwind CSS 静态导航栏,滚动时带有阴影,适用于 Vue 应用程序
我最初在我的博客上写了这篇文章——实际上只是为了我自己参考,因为我的下一个项目还会用到这段代码。不过我也想在这里分享一下。
如果你还没有使用 Tailwind 来满足你的 CSS 需求,我强烈推荐它。它现在是我产品构建工具包中的必备工具,而且它与 Vue.js 和 Nuxt 的工作流程完美契合,我无法想象要迁移到其他工具。
Tailwind 的一大特点是它把 JavaScript 留给了你。因此它与库无关。
对于我的大多数项目,我希望在导航栏下有平滑的阴影 - 这是我用来实现它的代码。
HTML
<nav
:class="{ 'scrolled': !view.atTopOfPage }"
class="fixed flex w-full bg-white border-b items-center justify-between flex-wrap p-5 m-auto top-0 animated">
</nav>
.scrolled
这里,当值为view.atTopOfPage
false时,我们添加类。
CSS
我有一个在整个应用程序中都会用到的导航栏组件,所以这段代码应该放在那里。PS:是的,从技术上来说,这是 SCSS……
nav {
z-index: 10
}
nav.scrolled {
@apply shadow-2xl;
border-bottom: 0px;
}
当导航栏具有类时,将阴影应用于导航栏scrolled
。
JavaScript
// in data, I like to store a view object with all
// the values I need for a component to manage
// it's 'view' state - ie loading,
// or in this case, if the user is at the top of the page or not
data () {
return {
view: {
atTopOfPage: true
}
}
},
// a beforeMount call to add a listener to the window
beforeMount () {
window.addEventListener('scroll', this.handleScroll);
},
methods: {
// the function to call when the user scrolls, added as a method
handleScroll(){
// when the user scrolls, check the pageYOffset
if(window.pageYOffset>0){
// user is scrolled
if(this.view.atTopOfPage) this.view.atTopOfPage = false
}else{
// user is at top of page
if(!this.view.atTopOfPage) this.view.atTopOfPage = true
}
}
}
结果
导航栏上呈现丝滑柔滑的阴影。不妨在我的产品Referextra.com上体验一下