.net快速开发平台

工作流+智能表单
帮助企业快速应对变化
像纸质笔记本一样给div,textarea添加行的分割线

想要给textarea添加一个背景图来实现

但是背景图有几个问题,

1、每个div或者textarea的line-height不一样,对于每个不同的line-height都需要一个不同的背景图

2、当有滚动条出现时,拉动滚动条背景图分割线不会变,导致样式错位

因此使用传统的图片作为背景图不可行,因为line-height是变化的,并且有滚动条的时候背景图也应该变化。

问题找到了,就要找到解决问题的访问,那就是使用canvas动态生成背景图。

具体不用讲解了,看代码,做成了一个jquery插件的形式。

直接调用$("textarea,div").backgroundLine();就行

截个图:

 

(function ($) { 
    var  setBG=function(_this) {
        if ($(_this).css("visibility") == "hidden" || $(_this).css("display") == "none" )
            return;
        var lineHeight = parseFloat($(_this).css("line-height"));
        if (isNaN(lineHeight)) {
            lineHeight = 25;
            $(_this).css("line-height", lineHeight + "px");
        }
        var padding = $(_this).scrollTop() % lineHeight;
        var bgimg = createBG(lineHeight, padding);
        if (bgimg != null) {
            $(_this).css("background", "url(" + bgimg + ")   repeat");
            $(_this).on("scroll", function () {
                var lineHeight = parseFloat($(_this).css("line-height"));
                var padding = $(_this).scrollTop() % lineHeight;
                var bgimg = createBG(lineHeight, padding);
                $(_this).css("background", "url(" + bgimg + ") left top repeat");
            });
        }
    } 
    this.___BGList = {};
    var createBG=function( height, padding) {
        var key = height + "-" + padding; 
        var width = 4;
        if (this.___BGList[key] != null) {
            return this.___BGList[key];
        }
        var canvas = document.createElement("canvas");
        if (canvas.getContext) {
            var context = canvas.getContext("2d");
            canvas.width = width;
            canvas.height = height;
            canvas.lineWidth = 1;
            canvas.fillStyle = "#000000";
            context.fillRect(0, height - padding - 1, 1, 1);
            var dataURL = canvas.toDataURL('image/png'); 
            this.___BGList[key] = dataURL;
            return dataURL;
        }
        return null;
    }
    $.fn.backgroundLine = function (options) {
        this.each(function () { 
            setBG(this);
        });
    };
})(jQuery);

 

posted on 2019-01-03 20:07  chegan  阅读(1270)  评论(1编辑  收藏  举报