如何根据php标题的长度调整margin-top属性?

时间:2013-08-29 17:41:00

标签: php javascript html css wordpress

我正在Wordpress中构建自定义模板。

如果页面标题大于45个字符,我需要自动调整页面标题。

标题是通过PHP从Wordpress数据库中提取的。

我正在尝试构建javascript来执行此操作:

如果标题的长度(通过php)是< 45个字符:将css属性“margin-top”更改为111px。

否则将css属性“margin-top”更改为150px。

这是我到目前为止所做的:

我的HTML:

<div class="title-of-page" id="title" style="margin-top:53px">
    <?php echo get_the_title($post->post_parent); ?>
</div>

我的Javascript:

<script>
if ( <? php strlen(get_the_title($post - > post_parent)) ?> < 45) {
    document.getElementById("title").style.marginTop = "111px";
} else {
    document.getElementById("title").style.marginTop = "150px";
} 
</script>

如果我不够清楚,请提问。

2 个答案:

答案 0 :(得分:1)

为什么选择javascript?

<?php
$title = get_the_title($post->post_parent);
if (strlen($title)<45) { $mtop ='111px'; } else { $mtop='150px'; }
echo '<div class="title-of-page" id="title" style="margin-top:'.$mtop.';">'.$title.'</div>';
?>

答案 1 :(得分:0)

你只能在@Thomas Martin建议的PHP中使用它。

但是,如果你太热衷于在Javascript Side这样做了。你可以做到。

<script>
   var title =  document.getElementById('title').textContent;
   if(title.length < 45){
       document.getElementById("title").style.marginTop = "111px";
   }else{
       document.getElementById("title").style.marginTop = "150px";
   }
</script>