[英]How can I add Wordpress php code into JavaScript
I have the following javascript code: 我有以下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')
}
});
Is it possible to insert a wp custom php code 是否可以插入一个wp自定义PHP代码
<?php the_custom_logo(); ?>
Instead of this static attribute 而不是这个静态属性
.attr('src','assets/images/logo.png');
Many thanks in advance. 提前谢谢了。
You need to set variable in template: 您需要在模板中设置变量:
<script>
var logoImage = <?php the_custom_logo(); ?>;
var logoImageFooter = <?php the_custom_logo()?> //here footer logo
</script>
and than, in your js file use it 而且,在你的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)
}
});
Your Js code: 你的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 code: 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>
IF you need jquery with php code input then wp_localize_script()
function. 如果你需要jquery与PHP代码输入然后
wp_localize_script()
函数。 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' );
You can access the variables in JavaScript as follows: 您可以按如下方式访问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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.