我正在尝试将 div 垂直放置在 Wordpress 窗口的中间。 我有一个包含以下代码的 function.js 文件:
function setToCenter()
{
var a = document.getElementById("R_center");
var h = window.innerHeight;
var p = (h/2)-(650/2);
if( p < 80 ){ p = 80; }//limit to header height
//a.style.transform = "transform(0,"+p+"px)";
//a.style.margin-top= p+"px";
a.style.paddingTop = p+"px";
}
和一个用于获取帖子内容的 php 文件:
<?php
/*
Template Name: Page R Center
*/
?>
<?php global $optimizer;?>
<?php get_header(); ?>
<div id="R_center" class="R">
<script type="text/javascript"> setToCenter(); </script>
<?php if(have_posts()): ?><?php while(have_posts()): ?><?php the_post(); ?>
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<div class="thn_post_wrap">
<?php the_content(); ?>
</div>
</div>
<?php endwhile ?>
</div><!--R_center class END-->
<?php endif ?>
<?php get_footer(); ?>
在我的 header.php 中:
<script type="text/javascript" src="http://localhost/wp/wp-content/themes/r-child/assets/js/functions.js"></script>
一切都运转良好。 Div 位于屏幕的垂直中间。但是因为 Div 是在 java 脚本之后渲染的,所以它只有在刷新页面后才起作用。 我的问题是我必须将 JavaScript 放在哪里以避免刷新?我可以执行functions.js 中的所有内容而不调用php 中的函数吗? 谢谢
最佳答案
在您的情况下,您需要在浏览器加载 DOM 后启动 setToCenter 函数。您应该将其包装为 DOMContentLoaded event ,例如:
document.addEventListener("DOMContentLoaded", function(event) {
setToCenter();
});
或者如果你使用 jQuery:
$(function(){
setToCenter();
});
关于javascript - 使用javascript使div垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32552448/