开放的编程资料库

当前位置:我爱分享网 > PHP教程 > 正文

使用 MooTools 或 PHP 的漂亮的 Word Wrapper

细节,细节,细节。细节是让一个好的网站更上一层楼的要素。链接微调(jQuery、MooTools)、简单但时尚的 CSS 增强和不透明效果等小细节是让您的网站比同类网站更具优势的厚颜无耻的效果。我们今天要解决的细节是“寡妇”文本。当一个长字符串中只有一个单词换行到下一行时,就会出现“寡妇”。一个例子是:

没有冒犯那里狂暴的美洲狮的意思,但寡妇看起来很不稳定。防止寡妇最好的方法就是加个“ ”在字符串中的最后一个和倒数第二个单词之间。这样做,上面的示例将像“或”一样拆分到下一个,这样两个词就会出现在第二行。今天,我将向您展示如何使用微型 MooTools 类或 PHP 来完成此任务。

MooTools JavaScript

//class
var WordWrapper = new Class({
	
	Implements: [Options],
	
	options: {
		elements: 'h1',
		minWords: 3
	},
	
	initialize: function(options) {
		this.elements = $$(options.elements);
		this.elements.each(function(el) {
			this.apply(el);
		},this);
	},
	
	apply: function(element) {
		var original = element.get('html'), arr = original.split(' ');
		if(arr.length >= this.options.minWords) {
			//join the last and second to last
			arr[arr.length - 2] += ' ' + arr[arr.length - 1];
			arr.pop();
			element.set('html',arr.join(' '));
		}
	}	
});

MooTools 插件只提供了几个选项:应用此选项的元素以及在替换发生之前元素必须具有的最少单词数。使用就像您期望的一样简单:

//usage
window.addEvent('domready',function() {
	var ww = new WordWrapper({
		elements: 'h2'
	});
});

//sample results
//"This Is The First Attempt" becomes: This Is The First Attempt
//"Leave Me" is not long enough to modify
//"Que?" is not long enough to modify
//"I Am, I Am SuperMan, And I Can Do Anything" becomes: I Am, I Am SuperMan, And I Can Do Anything

太棒了….但是 PHP 版本呢?当然可以,为什么不呢?

PHP

function word_wrapper($text,$minWords = 3) {
	$return = $text;
	$arr = explode(' ',$text);
	if(count($arr) >= $minWords) {
		$arr[count($arr) - 2].= ' '.$arr[count($arr) - 1];
		array_pop($arr);
		$return = implode(' ',$arr);
	}
	return $return;
}

瞧!现在您可以在任何文本到达 DOM 之前对其进行更新!

jQuery

想看看您如何使用 jQuery 完成这一壮举吗?跳转到 Chris Coyier 的 CSS-Tricks 博客文章找出答案!

未经允许不得转载:我爱分享网 » 使用 MooTools 或 PHP 的漂亮的 Word Wrapper

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏