因此,我拥有这个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