使用@Hemlocks,@布賴恩莫特森和@吉博的解決方案,我已經建立了一個jQuery插件來解決這個問題。
我也增加了使用.html()返回初始值的支持,而不是讓它返回當前的innerHTML。希望這將是有用的人......
(function($) {
$.trimLeft = function(element, options) {
var trim = this;
var $element = $(element), // reference to the jQuery version of DOM element
element = element; // reference to the actual DOM element
var initialText = element.innerHTML;
trim.init = function() {
overrideNodeMethod("html", function(){ return initialText; });
trimContents(element, element);
return trim;
};
trim.reset = function(){
element.innerHTML = initialText;
return trim;
};
//Overide .html() to return initialText.
var overrideNodeMethod = function(methodName, action) {
var originalVal = $.fn[methodName];
var thisNode = $element;
$.fn[methodName] = function() {
if (this[0]==thisNode[0]) {
return action.apply(this, arguments);
} else {
return originalVal.apply(this, arguments);
}
};
};
var trimContents = function(row, node){
while (row.scrollWidth > row.offsetWidth) {
var childNode = node.firstChild;
if (!childNode)
return true;
if (childNode.nodeType == document.TEXT_NODE){
trimText(row, node, childNode);
}
else {
var empty = trimContents(row, childNode);
if (empty){
node.removeChild(childNode);
}
}
};
};
var trimText = function(row, node, textNode){
var value = '\u2026' + textNode.nodeValue;
do {
value = '\u2026' + value.substr(4);
textNode.nodeValue = value;
if (value == '\u2026'){
node.removeChild(textNode);
return;
}
}
while (row.scrollWidth > row.offsetWidth);
};
trim.init();
};
$.fn.trimLeft = (function(options){
var othat = this;
var single = function(that){
if (undefined == $(that).data('trim')) {
var trim = new $.trimLeft(that, options);
$(that).data('trim', trim);
$(window).resize(function(){
$(that).each(function(){
trim.reset().init();
});
});
}
};
var multiple = function(){
$(othat).each(function() {
single(this);
});
};
if($(othat).length>1)
multiple(othat);
else
single(othat);
//-----------
return this;
});
})(jQuery);
使用啓動:
//Call on elements with overflow: hidden and white-space: nowrap
$('#container>div').trimLeft();
//Returns the original innerHTML
console.log($('#test').html());
fiddle
Ouch,混合RTL和LTR語言?最近我有很多問題。當我將每個RTL和LTR元素分隔到不同的div中時,我發現了很多幫助。否則,這兩種語言都會以一種相當奇怪的方式混合在一起...... – Zwik 2012-03-26 18:52:21
FWI:我在chrome問題上打開了一個錯誤:http://code.google.com/p/chromium/issues/detail?id = 155836 – Mbrevda 2013-02-13 10:26:08
[當需要使用正確的「文本溢出」時,「方向」設置爲「rtl」](http://stackoverflow.com/questions/18532256/needs-use-right-text-overflow- when-direction-is-set-to-rtl) – 2013-08-30 15:20:09