您可以使用 CSS 或 JavaScript 创建渐变为不透明吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4480919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:35:42  来源:igfitidea点击:

Can you create gradients that fade to opacity using CSS or JavaScript?

javascriptcssgoogle-chromeopacitygradient

提问by u365975

WebKit has introduced the ability to create CSS gradients. For example, with the following code:

WebKit 引入了创建 CSS 渐变的能力。例如,使用以下代码:

-webkit-gradient(linear, left top, left bottom, from(#fff), to(#000));

However, is it possible to have an opacity gradient using CSS? I want the gradient to be a single color on one side, and fade to zero opacity on the other.

但是,是否可以使用 CSS 实现不透明度渐变?我希望渐变在一侧是单一颜色,而在另一侧淡入零不透明度。

Cross-browser compatibility isn't important; I just need it to work in Google Chrome.

跨浏览器兼容性并不重要;我只需要它在谷歌浏览器中工作。

Is there some way to do this using CSS? If not, can something similar be done using JavaScript (not jQuery)?

有没有办法使用 CSS 来做到这一点?如果没有,可以使用 JavaScript(不是 jQuery)完成类似的事情吗?

Thanks for your help.

谢谢你的帮助。

采纳答案by Jasper

Yes

是的

for the colors, use rgba(x, y, z, o) where o is the opacity

对于颜色,使用 rgba(x, y, z, o) 其中 o 是不透明度

should work

应该管用

e.g.

例如

background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255, 255, 255, 1)), to(rgba(0, 0, 0, 0)));

Edit:For the final value (opacity) 1 is opaque & 0 is transparent

编辑:对于最终值(不透明度),1 是不透明的,0 是透明的

回答by antonj

Yup, rgba(red, green, blue, alpha)is what you should use http://www.w3.org/TR/css3-color/#rgba-color, example (Try it out on jsFiddle):

是啊,rgba(red, green, blue, alpha)是你应该用什么http://www.w3.org/TR/css3-color/#rgba-color,例如(试试吧上的jsfiddle):

/* Webkit */
background: -webkit-gradient(
    linear,
    left bottom,
    left top,
    color-stop(1, rgba(0,0,0,0.0)), /* Top */
    color-stop(0, rgba(0,0,0,1.0)) /* Bottom */
);

/* Gecko */
background: -moz-linear-gradient(
    center bottom,
    rgba(0,0,0,1.0) 0%, /* Bottom */
    rgba(0,0,0,0.0) 100% /* Top */
);

回答by oezi

not tested, but this should work (in FF this works (with a different syntax) - i'm not sure if safari/webkit knows rgba):

未经测试,但这应该有效(在 FF 中这有效(使用不同的语法)-我不确定 safari/webkit 是否知道 rgba):

-webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255,1)), to(rgba(0,0,0,0)));