はてなブログで動く蛍光ペンを使えるようにする方法
スクロールすると下線が引かれます。
吾輩わがはいは猫である。
名前はまだ無い。
使い方
hl
タグを書きます。2文字目は、イチではなくて
吾輩わがはいは猫である。<hl color="#ff99ff">名前はまだ無い。</hl>
設定の仕方
hl
タグが使えるようになります。
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.7/dist/vue.js"></script> <script> // DOM が描画されるまで待つ setTimeout(vue, 1000); function vue() { new Vue({ el: '#container', components: { hl: highlight(), } }); } // Just return a Vue component. function highlight() { return { template: '<span v-bind:style="highlighter">' + ' <slot></slot> ' + '</span>', props: ['color'], data: function() { return { highlighter: { 'background': 'linear-gradient(' + 'transparent, ' + this.color + ')', 'background-size': ' 0% 60%', 'background-position': '0% 100%', 'background-repeat': 'no-repeat', 'transition-delay': '1s', 'transition-duration': '2.5s', }, domRectTop: undefined, }; }, mounted: function() { domRect = this.$el.getBoundingClientRect(); this.domRectTop = domRect.top + window.scrollY; window.addEventListener('scroll', this.handleScroll); }, methods: { handleScroll: function() { // DOM の頭が表示画面の底よりも 200 px 高い位置に来たら線を引く viewPortBottom = window.scrollY + window.innerHeight; if (viewPortBottom - this.domRectTop > 200){ this.highlighter['background-size'] = '100% 60%'; } else { this.highlighter['background-size'] = ' 0% 60%'; } // console.log("%d, %d", viewPortBottom, this.domRectTop); }, }, } } </script>
駆け足で解説(なぐり書き)
以下の記事で解説しました。
ただし上記のコードとは、前半のこの部分が違います。 これは上のコードが、はてなブログ用に書かれているためです。
// DOM が描画されるまで待つ setTimeout(vue, 1000); function vue() { new Vue({ el: '#container', components: { hl: highlight(), } }); }