[英]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.