技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> JavaScript --> JavaScript获取准确的行高

JavaScript获取准确的行高

浏览:1423次  出处信息

    需求:n多行文字的div,隐藏超过5行的部分。

    分析:我能想到的有2种思路,一种是计算5行的文字个数,重新innerHTML。第二种给div设置高度,沿着第二个思路往下走,就是设置div的高度为5×lineheigh。

    解决:任务锁定到货的lineheight的问题上。css的设置会影响到lineheight。所以首先要获得css的lineheight与fontsize,如果有padding的话,也可以算进去。

    相关知识点:

    1,获取css不能通过element.style的方式,这只能获得内联样式,获得不到样式表中的定义。需要采用二级DOM。

以下是代码片段:
var style = _element.currentStyle || document.defaultView.getComputedStyle(_element,null);
    var value = style[_property]

    2,ie返回的单位是pt,ff返回的是px。需要pt到px的转换

以下是代码片段:
var px = parseInt(pt)*((1/72)*screen.deviceXDPI) +’px’;

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

以下是代码片段:
var defaultLineheight = fontsize*(7/6);

    把以上代码攒起来,封装一个设置隐藏多余行的类

以下是代码片段:
(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;
    }
    };
    })()
    调用

以下是代码片段:
<div id=”t1″>
千余字
</div>

以下是代码片段:
    var a1 = new AutoOverHider(’t1′);
    a1.hide(5);

    或者

以下是代码片段:
    var a1 = new AutoOverHider(’t1′,5);

QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1