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

How do I adjust margin-top attribute depending on length of php title?

本文关键字:调整 margin-top 属性 何根 php 标题      更新时间:2023-09-26

我正在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>

如果我不够清楚,可以提问。

为什么选择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>';
?>

您只能按照@Thomas Martin的建议在PHP中执行。

然而,如果你太热衷于在Javascript方面做这件事,你可以通过来做。

<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>