正文

今天在折腾网页背景的时候,把整个网站都给弄成透明的了,这样一来就可以弄一个动态的背景,我首先想到了CSS+jQuery,可是瞎搞了许久才发现没法和知更鸟主题兼容,两者必须舍弃一个,我自然是放弃了背景呗,然后想了下,还是把做好的背景发出来给小伙伴们参考参考吧。

HTML代码

<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script src="gradientify.js"></script>
<link rel="stylesheet" href="main.css">
<script>
    $(document).ready(function() {
        $("body").gradientify({
            gradients: [
                { start: [49,76,172], stop: [242,159,191] },
                { start: [33,229,241], stop: [235,236,117] }
            ]
        });
    });
</script>

CSS代码

*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
body{color:#ffffff;font:18px/1.5 'Ubuntu',sans-serif}
h1{margin-top:0;margin-bottom:0.5em}
p{margin-top:0;margin-bottom:2em}
h1{font-size:60px;font-weight:bold}
#wrapper{position:absolute;top:50%;left:50%;margin-top:-130px;margin-left:-300px;height:260px;width:600px;text-align:center}

jQuery代码

;window.Modernizr=function(a,b,c){function u(a){i.cssText=a}function v(a,b){return u(l.join(a+";")+(b||""))}function w(a,b){return typeof a===b}function x(a,b){return!!~(""+a).indexOf(b)}function y(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:w(f,"function")?f.bind(d||b):f}return!1}var d="2.8.3",e={},f=b.documentElement,g="modernizr",h=b.createElement(g),i=h.style,j,k={}.toString,l=" -webkit- -moz- -o- -ms- ".split(" "),m={},n={},o={},p=[],q=p.slice,r,s={}.hasOwnProperty,t;!w(s,"undefined")&&!w(s.call,"undefined")?t=function(a,b){return s.call(a,b)}:t=function(a,b){return b in a&&w(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=q.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(q.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(q.call(arguments)))};return e}),m.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return u((a+"-webkit- ".split(" ").join(b+a)+l.join(c+a)).slice(0,-a.length)),x(i.backgroundImage,"gradient")};for(var z in m)t(m,z)&&(r=z.toLowerCase(),e[r]=m[z](),p.push((e[r]?"":"no-")+r));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)t(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof enableClasses!="undefined"&&enableClasses&&(f.className+=" "+(b?"":"no-")+a),e[a]=b}return e},u(""),h=j=null,e._version=d,e._prefixes=l,e}(this,this.document);
(function ($, window, document, undefined) {
    'use strict';
    var pluginName = 'gradientify',
        defaults = {
            angle: '0deg',
            fps: 60,
            gradients: {},
            transition_time: 8
        };
    function Plugin(element, options) {
        this.element = element;
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }
    $.extend(Plugin.prototype, {
        init: function () {
            if (!Modernizr.cssgradients) {
                return;
            }
            this.currentIndex = 0;
            this.nextIndex = 1;
            this.steps_count = 0;
            this.steps_total = Math.round(this.settings.transition_time * this.settings.fps);
            this.rgb_steps = {
                start: [0, 0, 0],
                stop: [0, 0, 0]
            };
            this.rgb_values = {
                start: [0, 0, 0],
                stop: [0, 0, 0]
            };
            this.prefixes = ['-webkit-', '-moz-', '-o-', '-ms-', ''];
            this.color1 = null;
            this.color2 = null;
            this.calculateSteps();
            setInterval(function() {
                this.updateGradient.apply(this);
            }.bind(this), Math.round(10 / this.settings.fps));
        },
        setNext: function (num) {
            return (num + 1 < this.settings.gradients.length) ? num + 1 : 0;
        },
        calculateStepSize: function (a, b) {
            return (a - b) / this.steps_total;
        },
        calculateSteps: function () {
            for (var key in this.rgb_values) {
                if (this.rgb_values.hasOwnProperty(key)) {
                    for (var i = 0; i < 3; i++) {
                        this.rgb_values[key][i] = this.settings.gradients[this.currentIndex][key][i];
                        this.rgb_steps[key][i] = this.calculateStepSize(this.settings.gradients[this.nextIndex][key][i], this.rgb_values[key][i]);
                    }
                }
            }
        },
        updateGradient: function () {
            var i;
            for (var key in this.rgb_values) {
                if (this.rgb_values.hasOwnProperty(key)) {
                    for (i = 0; i < 3; i++) {
                        this.rgb_values[key][i] += this.rgb_steps[key][i];
                    }
                }
            }
            var t_color1 = 'rgb(' + (this.rgb_values.start[0] | 0) + ',' + (this.rgb_values.start[1] | 0) + ',' + (this.rgb_values.start[2] | 0) + ')';
            var t_color2 = 'rgb(' + (this.rgb_values.stop[0] | 0) + ',' + (this.rgb_values.stop[1] | 0) + ',' + (this.rgb_values.stop[2] | 0) + ')';
            if (t_color1 != this.color1 || t_color2 != this.color2) {
                this.color1 = t_color1;
                this.color2 = t_color2;
                $(this.element).css('background-image', '-webkit-gradient(linear, left bottom, right top, from(' + this.color1 + '), to(' + this.color2 + '))');
                for (i = 0; i < 4; i++) {
                    $(this.element).css('background-image', this.prefixes[i] + 'linear-gradient(' + this.settings.angle + ', ' + this.color1 + ', ' + this.color2 + ')');
                }
            }
            this.steps_count++;
            if (this.steps_count > this.steps_total) {
                this.steps_count = 0;
                this.currentIndex = this.setNext(this.currentIndex);
                this.nextIndex = this.setNext(this.nextIndex);
                this.calculateSteps();
            }
        }
    });
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
        });
    };
})(jQuery, window, document);

使用方法

将CSS代码写进main.css文件,将jQuery代码写进gradientify.js文件,将html代码放到index即可,当然了,还要处理兼容问题喔!

效果图

Last modification:December 5th, 2019 at 01:04 pm
如果觉得我的文章对你有用,请随意赞赏