簡體   English   中英

使用javascript垂直居中div

[英]using javascript to vertically center a div

我正在嘗試在WordPress中的窗口中間垂直放置div。 我有一個帶有以下代碼的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>

evrything運作良好。 該Div位於屏幕的垂直中間。 但是,因為Div是在Java腳本之后呈現的,所以它僅在刷新頁面后才起作用。 我的問題是我必須在哪里放置JavaScript以避免刷新? 我可以執行我的functions.js中的所有內容而無需在PHP中調用函數嗎? 謝謝

對於您的情況,您需要在瀏覽器加載DOM之后啟動setToCenter函數。 您應該將其包裝到DOMContentLoaded event中 ,例如:

document.addEventListener("DOMContentLoaded", function(event) {
    setToCenter();
});

或者,如果您使用jQuery:

$(function(){
    setToCenter();
});

最簡單的方法是將函數調用放在頁腳附近,即使您也可以將其放在頁腳之后。 這將解決您的問題。 您問過“可以將代碼放在function.js中嗎?” 是的,您也可以這樣做。 只需將函數調用放在window.load函數內部,然后將此代碼放入function.js文件即可。 以下是這兩種情況的示例。

$(window).load(function() { setToCenter(); });

要么

<?php
/*
Template Name: Page R Center 
*/
?>
<?php global $optimizer;?>
<?php get_header(); ?>

            <div id="R_center" class="R">

                    <?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(); ?>
<script type="text/javascript"> setToCenter(); </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM