Created
September 20, 2019 02:22
-
-
Save ma2i/6701df308bfbec75fcfe0e2f8b7cb406 to your computer and use it in GitHub Desktop.
【WordPress】見出しを画面上部に固定表示する方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
① プラグイン「Easy Table of Contents」 は入れておく | |
② ページのスクロールと連動し、今読んでいるコンテンツの見出しが画面上部に固定表示される | |
*/ | |
//上部固定の見出しラベルを作るよ | |
function kjk_fixed_headline_script() { | |
?> | |
<style> | |
.kjk_fixed_headline { | |
width: 100%; | |
position: fixed; | |
top: 0; | |
padding-left: 10px; | |
background-color: #899cff; | |
color: #fff; | |
font-size: 14px; | |
font-weight: bold; | |
z-index: 50; | |
} | |
</style> | |
<script> | |
jQuery(function() { | |
var posArray = new Array(); | |
var count = 1; | |
var block = ''; | |
var flag = 0; | |
var pos = 0; | |
posArray.length = 0; | |
function fixed_headline() { | |
jQuery('.entry-content h2,.entry-content h3,.entry-content h4,.entry-content h5,.entry-content h6').each(function(i){ | |
posArray[i] = jQuery(this).offset().top; | |
block += '<span class="kjk_fixed_headline headline-' + count + '"><i class="fa fa-chevron-circle-right" aria-hidden="true"></i> ' + jQuery(this).text() + '</span>'; | |
count ++; | |
}); | |
posArray[posArray.length] = jQuery('.article-footer').offset().top; | |
jQuery('.footer').after('<div class="kjk_fixed_headline_block">' + block + '</div>'); | |
jQuery(window).scroll(headline_scroll).trigger('scroll'); | |
} | |
function headline_scroll() { | |
pos = jQuery(window).scrollTop(); | |
if ( pos > posArray[flag-1] && pos < posArray[flag] ) { | |
visible(flag); | |
} else if ( pos < posArray[0] || pos < posArray[flag-1] || pos > posArray[flag] ) { | |
hidden(); | |
for (var i = posArray.length; i>=0; i--) { | |
if ( pos > posArray[posArray.length]) { | |
flag = 0; | |
break; | |
} else if ( pos > posArray[i-1] ) { | |
flag = i; | |
break; | |
} | |
} | |
} | |
} | |
function visible(i) { | |
jQuery('.kjk_fixed_headline_block .headline-' + i).css({'visibility': 'visible'}).fadeIn('normal'); | |
} | |
function hidden() { | |
jQuery('.kjk_fixed_headline_block span').css({'visibility': 'hidden'}).fadeOut('fast'); | |
} | |
jQuery(window).load(function () { | |
fixed_headline(); | |
}); | |
}); | |
</script> | |
<?php | |
} | |
add_action( 'wp', 'kjk_check_single' ); | |
function kjk_check_single() { | |
if ( is_single() ) { | |
add_action('wp_footer', 'kjk_fixed_headline_script'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment