多行文本截斷

/*
* 文字截取
* create by:river
* create date : 2014/08/15
* 文字截取兩種方式截取,按字數,按行數
* 分別經過相應自定義屬性
* data-textflow-words 字數
* data-textflow-rows  行數
*/
Ymt.add(function (require, exports, module) {
    var defOpts = {
        defSel: '.textflow',//默認選擇
        rowNum:3,
        ellipsis:"..."//超出替換符號
    }
    /*
    * 字數截取
    * @param {objcet} 截取對象
    * @param {number} 行數
    */
    function wordsIntercept($target, wordsNum) {
        $target.each(function () {

        })
    }
    /*
    *行高截取
    * @param {objcet} 截取對象
    * @param {number} 行數
    */
    function RowIntercept($target,rowNum) {
        $target.each(function () {
            var $this = $(this),
                clientHeight = this.clientHeight,//容器高度
                fontSize = parseFloat($this.css("fontSize")),
                lineHeight = parseFloat($this.css("lineHeight"));
            var title = $this.attr("title");
            //將原來的值保存到title中
            if (title === undefined || title === "") {
                $this.attr("title", title = $this.text());
            }
            //將原來的值還原從新計算
            $this.text(title);

            var dheight = parseInt(rowNum * lineHeight);
            if (clientHeight >= dheight) {
                while (dheight * 3 < this.clientHeight) {
                    $this.text(title.substring(0, title.length / 2));
                    title = $this.text();
                }
                //減去末尾文字
                while (dheight < this.clientHeight) {
                    title = $this.text();
                    $this.text(title.replace(/(\s)*([a-zA-Z0-9]?|\W)(\.\.\.)?$/, "..."));
                }
            }
        })
    }
    /**
    * @param {string} 選擇器
    * @param {string} 子選擇器
    *   子選擇器的目的,在父元素定義自定義屬性,全部子選擇應用這個選項,就不須要每一個標籤都去定義截取方式。        
    * @param {object} 配置項
    */
    return function (selector, childer, opts) {
        var $target, num, $childer;
        opts = opts || defOpts;
        //若是沒有傳入使用默認
        if (!arguments.length || typeof arguments[0] !== "string") {
            $childer = $target = $(".textflow");
        } else {
            $childer = $target = $(selector);
        }
        //判斷是否有配置項
        if (opts === "objcet") {
            opts = $m.merge(defOpts, opts);
        }
        //判斷是否有子項
        if (typeof arguments[1] === "string") {
            $childer = $target.find(childer);
        }
        //按行截取大於按字數截取
        if (num = $target.attr("data-textflow-rows") || opts.rowNum) {
            RowIntercept($childer, num);
            return;
        }
        if (num = $target.attr("data-textflow-words")) {
            wordsIntercept($childer, num);
        }
        
    }
})
相關文章
相關標籤/搜索