javascript - 使用javascript使div垂直居中

标签 javascript php css wordpress

我正在尝试将 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/

相关文章:

javascript - 有人可以帮助我使用这个 javascript 正则表达式将列表项字符串转换为仅包含项目文本的数组(没有列表项 # 或换行符)

php - 数据库设计数值范围

php - 如何在顺序div中显示mysql查询结果

html - WordPress CSS 背景图像未出现

javascript - 使用 jquery 的响应式弹出 div

html - CSS/HTML 列高问题

javascript - 为什么 uibmodals 只能在第二次调用时拖动?

javascript - 企业 JavaScript 技巧

JavaScript,要求用户插入一个数字并判断它是否是素数

php - 如何生成带有金额的以太坊二维码地址?