2011-08-13 20 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進行格式化。

相關問題