如何使用javascript获取从容器中分离出来的元素的宽度


How to get the width of an element that breaks out of its container with javascript?

我想为WordPress制作一个小插件,检查是否有任何标题从容器中弹出,以及是否应该编辑字体大小。

我的PHP遍历了每一页和每一篇文章的所有标题。然后,它从标题中取出每个单词,并将它们放入一个数组中。然后,它检查所有标题中最长的单个单词,并将其回声输出。

然后,如果网站中最长的单词不适合其容器,我想使用javascript来提醒,这样我就可以使用响应式设计,并为所有窗口大小插入正确的字体大小。

这是我的PHP(它有效,但我是一名设计师,所以这可能是垃圾。当然,你可以建议改进):

$all = array();
// posts
$custom_query = new WP_Query('cat=-999999'); 
while($custom_query->have_posts()) : $custom_query->the_post(); 
$title  = get_the_title();
$pieces = explode(" ", $title);
$all = array_merge($pieces, $all);
endwhile;
wp_reset_postdata();
//pages
query_posts( 'post_type=page&posts_per_page=999999999' ); 
if (have_posts()) : while (have_posts()) : the_post(); 
$title  = get_the_title();
$pieces = explode(" ", $title);
$all = array_merge($pieces, $all);
endwhile; 
endif; 
$lengths = array_map('strlen', $all);
$maxLength = max($lengths);
$index = array_search($maxLength, $lengths);
$longestHeading = $all[$index];
echo "<h1>" .  $longestHeading . "</h1>";

标题的宽度等于它的容器,尽管它是分开的。我想知道它是否爆发并且比容器长,然后提醒用户。

谢谢!

要获得h1的实际值,需要添加两个属性:

div{
  width:300px;
  border:1px dashed grey;
  white-space:nowrap;
}

添加nowrap以避免标题换行。和:

h1 {
  display:inline-block;
}

添加inline-block以打破h1的块状态,保持其内容的宽度。

检查CodePen