zoukankan      html  css  js  c++  java
  • 像纸质笔记本一样给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);
  • 相关阅读:
    【Android平台安全方案】の #00-请不要在外部存储(SD卡)加密存储的敏感信息
    本学习笔记TCP/IP传输协议
    iOS_23_undress Girl
    uva 1560
    IOS开发-Swift新语言初见
    39个让你受益的HTML5教程
    ubuntu12.04管理员账户登录不了桌面,仅仅能客人会话登录
    怎样使用SetTimer MFC 够具体
    ArcGIS API for Silverlight 编辑Geometry
    几种更新(Update语句)查询的方法
  • 原文地址:https://www.cnblogs.com/chegan/p/10216577.html
Copyright © 2011-2022 走看看