#grad { background: -webkit-linear-gradient(red, blue); /* Safari 5.1 - 6.0 */ background: -o-linear-gradient(red, blue); /* Opera 11.1 - 12.0 */ background: -moz-linear-gradient(red, blue); /* Firefox 3.6 - 15 */ background: linear-gradient(red, blue); /* 标准的语法 */ }
上面是c3的实现方法,但是现在对c3的支持不是很好,所以只有通过其他的方式来实现。
下面则是用js来实现
var setGradient = (function() { //private variables; var p_dCanvas = document.createElement('canvas'); var p_useCanvas = !!(typeof(p_dCanvas.getContext) == 'function'); var p_dCtx = p_useCanvas ? p_dCanvas.getContext('2d') : null; var p_isIE = /*@cc_on!@*/ false; //test if toDataURL() is supported by Canvas since Safari may not support it try { p_dCtx.canvas.toDataURL() } catch(err) { p_useCanvas = false; }; if(p_useCanvas) { return function(dEl, sColor1, sColor2, bRepeatY) { if(typeof(dEl) == 'string') dEl = document.getElementById(dEl); if(!dEl) return false; var nW = dEl.offsetWidth; var nH = dEl.offsetHeight; p_dCanvas.width = nW; p_dCanvas.height = nH; var dGradient; var sRepeat; // Create gradients if(bRepeatY) { dGradient = p_dCtx.createLinearGradient(0, 0, nW, 0); sRepeat = 'repeat-y'; } else { dGradient = p_dCtx.createLinearGradient(0, 0, 0, nH); sRepeat = 'repeat-x'; } dGradient.addColorStop(0, sColor1); dGradient.addColorStop(1, sColor2); p_dCtx.fillStyle = dGradient; p_dCtx.fillRect(0, 0, nW, nH); var sDataUrl = p_dCtx.canvas.toDataURL('image/png'); with(dEl.style) { backgroundRepeat = sRepeat; backgroundImage = 'url(' + sDataUrl + ')'; backgroundColor = sColor2; }; } } else if(p_isIE) { p_dCanvas = p_useCanvas = p_dCtx = null; return function(dEl, sColor1, sColor2, bRepeatY) { if(typeof(dEl) == 'string') dEl = document.getElementById(dEl); if(!dEl) return false; dEl.style.zoom = 1; var sF = dEl.currentStyle.filter; dEl.style.filter += ' ' + ['progid:DXImageTransform.Microsoft.gradient( GradientType=', +(!!bRepeatY), ',enabled=true,startColorstr=', sColor1, ', endColorstr=', sColor2, ')'].join(''); }; } else { p_dCanvas = p_useCanvas = p_dCtx = null; return function(dEl, sColor1, sColor2) { if(typeof(dEl) == 'string') dEl = document.getElementById(dEl); if(!dEl) return false; with(dEl.style) { backgroundColor = sColor2; }; //alert('your browser does not support gradient effet'); } } })(); setGradient('nth2', '#012D5E', '#07779D', 1);
第一个参数是容器名(id)接下来则是起始颜色和结束颜色,最后1代表从左到右 0表示从上到下