我有以下javascript代码:
$(window).scroll(function() {
if($(this).scrollTop() > 50) /*height in pixels when the navbar becomes non opaque*/
{
$('.navbar-default').addClass('sticky');
$('.navbar-brand img').attr('src','assets/images/logo.png'); //change src
} else {
$('.navbar-default').removeClass('sticky');
$('.navbar-brand img').attr('src','assets/images/logo__footer.png')
}
});
是否可以插入wp自定义php代码
<?php the_custom_logo(); ?>
代替此静态属性
.attr('src','assets/images/logo.png');
非常感谢。
答案 0 :(得分:4)
您需要在模板中设置变量:
<script>
var logoImage = <?php the_custom_logo(); ?>;
var logoImageFooter = <?php the_custom_logo()?> //here footer logo
</script>
然后,在您的js文件中使用它
$(window).scroll(function() {
if($(this).scrollTop() > 50) /*height in pixels when the navbar becomes non opaque*/
{
$('.navbar-default').addClass('sticky');
$('.navbar-brand img').attr('src',logoImage); //change src
} else {
$('.navbar-default').removeClass('sticky');
$('.navbar-brand img').attr('src',logoImageFooter)
}
});
答案 1 :(得分:1)
您的Js代码:
$(window).scroll(function() {
if($(this).scrollTop() > 50) /*height in pixels when the navbar becomes non opaque*/
{
$('.navbar-default').addClass('sticky');
$('.navbar-brand img').attr('src','custom_logo.png'); //change src
} else {
$('.navbar-default').removeClass('sticky');
$('.navbar-brand img').attr('src','logo_footer.png')
}
});
HTML代码:
<?php $customLogo= 'custom_logo'; ?>
<?php $footerLogo= 'footer_logo'; ?>
<html>
<body>
<script type="text/javascript">
// notice the quotes around the ?php tag
var customLogo="<?php echo $customLogo; ?>";
var footerLogo="<?php echo $footLogo; ?>";
alert(customLogo);
alert(footerLogo);
</script>
</body>
</html>
答案 2 :(得分:1)
如果您需要使用php代码输入然后使用wp_localize_script()
函数的jquery。
More information
var logoImage = <?php the_custom_logo(); ?>;
var logoImageFooter = <?php the_custom_logo()?> //here footer logo
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$translation_array = array(
'logo_image' => the_custom_logo(),
'logo_image_footer' => the_custom_logo()'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
您可以按以下方式访问JavaScript中的变量:
<script>
alert( object_name.logo_image);
alert( object_name.logo_image_footer);
</script>
$('.navbar-brand img').attr('src',object_name.logo_image); //change src