因此,我擁有這個H3標題,我想把它放在一半,然後用一個跨度來包裝它。 問題是標題可以有4個字,或2或5等,我只是可以弄清楚如何將標題分成一半(或多或少)。將標題分成兩半,或者接近中間位置
所以我想從去:
<h3>Some random title goes here</h3>
這樣:
<h3>Some random <span class="green">title goes here</span></h3>
PHP或JavaScript,任何事情都會發生。
因此,我擁有這個H3標題,我想把它放在一半,然後用一個跨度來包裝它。 問題是標題可以有4個字,或2或5等,我只是可以弄清楚如何將標題分成一半(或多或少)。將標題分成兩半,或者接近中間位置
所以我想從去:
<h3>Some random title goes here</h3>
這樣:
<h3>Some random <span class="green">title goes here</span></h3>
PHP或JavaScript,任何事情都會發生。
在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>'
);
});
如果您有標題,請獲取它的長度。然後,從長度的一半開始搜索下一個單詞邊界 - 通常這是一個空格字符。一旦你有了這個位置,你就知道在哪裏分裂。或者看看wordwrap()。
分解成詞,然後插入在大致中間可以工作:
<?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);
?>
我不知道你想多麼複雜這項工作。如果你不想讓它分成單詞,你是否滿意於簡單地在標題的中間點注入跨度?當然,這意味着在開始的時候沒有考慮注射。
在人物等級進樣:
<?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>
可能其他示例工作,但這是接近我。 非常感謝很多人!非常棒! –
嗯,這是可行的。但它相當醜陋。
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
我會測試這個,聽起來不錯!無論如何,PHP和地板似乎工作,這也應該!非常感謝 ! –
由於某種原因,這不會火...但一般的ideea是好的 –
我修復了代碼。 – keks