一个简单的Jquery Plugin: 跨浏览器的Word Breaker

本文介绍了一个基于jQuery的插件,该插件能够实现文本的强制换行效果,适用于需要控制文本显示方式的Web应用中。通过修改文本节点的属性来确保文本能够正确换行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://snippets.dzone.com/posts/show/6271

测试过,不错。

(function($) {
$.fn.breakWords = function() {
this.each(function() {
if(this.nodeType !== 1) { return; }

if(this.currentStyle && typeof this.currentStyle.wordBreak === 'string') {
//Lazy Function Definition Pattern, Peter's Blog
//From http://peter.michaux.ca/article/3556
this.runtimeStyle.wordBreak =
'break-all';
}
else if(document.createTreeWalker) {

//Faster Trim in Javascript, Flagrant Badassery
//http://blog.stevenlevithan.com/archives/faster-trim-javascript

var trim = function(str) {
str = str.replace(/^/s/s*/,
'');
var ws = //s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
};

//Lazy Function Definition Pattern, Peter
's Blog
//From http://peter.michaux.ca/article/3556

//For Opera, Safari, and Firefox
var dWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT, null, false);
var node,s,c = String.fromCharCode('8203');
while (dWalker.nextNode()) {
node = dWalker.currentNode;
//we need to trim String otherwise Firefox will display
//incorect text-indent with space characters
s = trim( node.nodeValue ).split('').join(c);
node.nodeValue = s;
}
}
});

return this;
};
})(jQuery);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值