javascript获取准确的行高

LlinZzi 发布于2008-11-19 01:39 | 82次阅读 | 字体: 打印预览


需求:n多行文字的div,隐藏超过5行的部分。
分析:我能想到的有2种思路,一种是计算5行的文字个数,重新innerHTML。第二种给div设置高度,沿着第二个思路往下走,就是设置div的高度为5×lineheigh。
解决:任务锁定到货的lineheight的问题上。css的设置会影响到lineheight。所以首先要获得css的lineheight与fontsize,如果有padding的话,也可以算进去。

相关知识点:
1,获取css不能通过element.style的方式,这只能获得内联样式,获得不到样式表中的定义。需要采用二级DOM。
photo 程序代码
var style = _element.currentStyle || document.defaultView.getComputedStyle(_element,null);
var value = style[_property]

2,ie返回的单位是pt,ff返回的是px。需要pt到px的转换
photo 程序代码
var px = parseInt(pt)*((1/72)*screen.deviceXDPI) +px;

3,ie在没有设置lineheight的情况下会返回‘normal,normal的数值究竟是多少?浏览器的默认高度是多少?没找到理论依据,希望了解的朋友提供下。我计算出来的如下公式。ie和ff都如此,但ff是可以读出默认数值的。所以似乎也没有计算的必要。
photo 程序代码
var defaultLineheight = fontsize*(7/6);


把以上代码攒起来,封装一个设置隐藏多余行的类
photo 程序代码
(function(){

var AutoOverHider = function() { this.init.apply(this,arguments);};

AutoOverHider.prototype = {
init:function(_element,_maxLine){
this.element = document.getElementById(_element);
if(_maxLine) this.hide(_maxLine);
},
hide:function(_maxLine){
this.maxLine = _maxLine;
var lineHeight = this._getStyle(lineHeight);
if(lineHeight==normal) { lineHeight = 7/6+;}
if(lineHeight.substr(lineHeight.length-2)!=px) lineHeight = lineHeight * parseInt(this._getStyle(fontSize)) + px;
var paddingHeight = this._getStyle(paddingBottom);
alert(paddingHeight);
this.height = this.maxLine * parseInt(lineHeight) - parseInt(paddingHeight);
this.element.style.height = this.height + px;
this.element.style.overflow = hidden;
},
show:function(){
this.element.style.height = auto;
},
_getStyle:function(_property,_element){
_element = _element||this.element;
var style = _element.currentStyle || document.defaultView.getComputedStyle(_element,null);
var value = style[_property]
if(/*@cc_on!@*/0 ) {
if(value.substr(value.length-2)==pt)
value = parseInt(value)*((1/72)*screen.deviceXDPI) +px;
}
return value;
}
};


})()


调用
photo 程序代码

千余字


var a1 = new AutoOverHider(t1);
a1.hide(5);
或者
var a1 = new AutoOverHider(t1,5);

本文出处 : http://onewww.net/blog/article.asp?id=123 end

上一篇:陕西知名报纸《华商报》报导“人肉防御”概念

下一篇:Google AdSense 新代码的怪现象