2011-08-13 16 views
1

因此,我拥有这个H3标题,我想把它放在一半,然后用一个跨度来包装它。 问题是标题可以有4个字,或2或5等,我只是可以弄清楚如何将标题分成一半(或多或少)。将标题分成两半,或者接近中间位置

所以我想从去:

<h3>Some random title goes here</h3> 

这样:

<h3>Some random <span class="green">title goes here</span></h3> 

PHP或JavaScript,任何事情都会发生。

回答

1

在javascript中,你可以使用jQuery:

$('h3').each(function(i,el){ 
    el = $(el); 
    var title = el.text().split(' '); 
    el.html(
    title.splice(0, Math.floor(title.length/2)).join(' ') 
     + ' <span>' + title.join(' ') + '</span>' 
); 
}); 

应该工作,没有测试过,虽然 作品。

编辑: 在评论中出现问题,如果我们只有一个单词,在<h3>末尾仍然有<span></span>。为了防止这种情况,我们可以事先检查它:

$('h3').each(function(i,el){ 
    el = $(el); 
    var title = el.text().split(' '); 
    if(title.length === 1) 
    return; 
    el.html(
    title.splice(0, Math.floor(title.length/2)).join(' ') 
     + ' <span>' + title.join(' ') + '</span>' 
); 
}); 
+0

我会测试这个,听起来不错!无论如何,PHP和地板似乎工作,这也应该!非常感谢 ! –

+0

由于某种原因,这不会火...但一般的ideea是好的 –

+0

我修复了代码。 – keks

2

如果您有标题,请获取它的长度。然后,从长度的一半开始搜索下一个单词边界 - 通常这是一个空格字符。一旦你有了这个位置,你就知道在哪里分裂。或者看看wordwrap()

+0

除非你想按像素大小分割一半。众所周知的英语谚语“WWWWWWWWWW iiiiiiiiii”可能是这种方法失败的最好例子。尽管其他大多数文本都可以正常工作。 :) – GolezTrol

+0

@GolezTrol为什么会失败?我当然会使用等宽字体。 :) – Shi

+0

是的,我也通过将文本标记为代码。不得不修改我的评论来证明我的观点。 ;-) – GolezTrol

0

分解成词,然后插入在大致中间可以工作:

<?PHP 
$string = 'this is an odd string'; 
$insert = '<tag>'; 
$words = explode(' ', $string); 
$half = round(count($words)/2); 
array_splice($words, $half, 0, $insert); 
print join(' ', $words); 
?> 
2

我不知道你想多么复杂这项工作。如果你不想让它分成单词,你是否满意于简单地在标题的中间点注入跨度?当然,这意味着在开始的时候没有考虑注射。

在人物等级

进样:

<?php 

$title = 'Some random title goes here'; 
$half_index = floor(strlen($title)/2); 
$split_title = substr($title, 0, $half_index) . '<span class="green">' . substr($title, $half_index) . '</span>'; 

?> 

<h3><?php echo $split_title ?></h3> 

注入至少字的级别:

<?php 

$title = 'Some random title goes here'; 
$words = preg_split('/ /', $title); 
$half_index = floor(count($words)/2); 
$split_title = 
    implode(' ', array_slice($words, 0, $half_index)) . ' '. 
    '<span class="green">' . implode(' ', array_slice($words, $half_index)) . '</span>'; 

?> 

<h3><?php echo $split_title ?></h3> 
+0

可能其他示例工作,但这是接近我。 非常感谢很多人!非常棒! –

1

嗯,这是可行的。但它相当丑陋。

var old = $('h3').text(); 
var words = old.split(' '); 
var new_text = words[0] + ' ' + words[1] + ' ' + words[2]; 
var span_content = ''; 
for(i = 3; i < words.length; i++){ 
    span_content += words[i] + ' ' 
} 
span_content = span_content.trim(); 
new_text += '<span class="green">' + span_content + '</span>'; 
$('h3').html(new_text); 

如果你打算做的只是隐藏文本,你也可以在CSS中做类似的事情。它被称为text-overflow: ellipsis http://www.quirksmode.org/css/textoverflow.html

0

如何:

$str = "Some random title goes here"; 
$format = "<h3>%s<span class='green'>%s</h3>"; 
vprintf($format, explode('&nbsp;', wordwrap($str, strlen($str)/2, '&nbsp;'), 2)); 

使用wordwrap让你不要在一个单词的中间裂开。然后,您使用explode仅根据返回的内容将字符串拆分为两个块,最后使用vprintf进行格式化。

相关问题