0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UIkitとVue.jsでScrollUpボタンを制作する

Posted at

Vue.jsで動くプラグインもあるようなのですが、自作してみました。

プラグイン
https://www.npmjs.com/package/vue-scroll-up

  • CSSフレームワークのUIkitを使って、ページのトップへスクロールするボタンを作成
  • Vue.jsでスクロールがある程度動いたらボタンを表示する

という分担で作りました。

ボタンの作成

<div id="scrollUp">
	<a class="scrollup" v-scroll="handleScroll" href="#" uk-scroll><span>ページトップへ</span></a>
</div>

これをbody内の一番下に追加

CSSで


.scrollup {
	opacity: 0;
	transition: all 0.4s ease 0s;
}

って書いておきます。

スクロールしたら表示するようにする

vue.jsを使って記述します。
ちなみに参考にしたのは、vue.jsのドキュメントにある
https://jp.vuejs.org/v2/cookbook/creating-custom-scroll-directives.html
スクロールイベントの記述例をちょっとだけカスタマイズしただけです。

Vue.directive('scroll', {
  inserted: function (el, binding) {
    let f = function (evt) {
      if (binding.value(evt, el)) {
        window.removeEventListener('scroll', f)
      }
    }
    window.addEventListener('scroll', f)
  }
})

// main app
new Vue({
  el: '#scrollUp',
  methods: {
    handleScroll: function (evt, el) {
      if (window.pageYOffset > 50) {
        el.setAttribute(
          'style',
          'opacity: 0.8;'
        )
      } else {
        el.setAttribute(
          'style',
          'opacity: 0;'
        )
      }
    }
  }
})

参考にしたドキュメントだと、一回表示されたボタンが上に上がっても消えない仕様になっていたので、上まで上がったらボタンがまた消えるように修正しました。

あと、ドキュメント通り「window.scrollY」を使うとIE11では動きません!!なので「window.pageYOffset」に変更。

以上です。

UIkitだけでできるよ〜って方いましたら教えてください。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?