繁体   English   中英

延迟背景颜色的不透明度,直到加载背景图像

[英]Delay background color opacity until background image loads

我想通过不透明的彩色屏幕在网站标题中看到背景图像。 背景图片是在CSS文件中设置的,并且已经过优化,因此无法将其缩小。 清除缓存后,即使在相当快速的Internet连接(〜150 mbps)上进行了完全优化,也可以看到图像加载缓慢。

所以我的问题是:有没有办法延迟不透明度-即使用背景屏幕的纯色版本-直到背景图像完全加载,然后切换到不透明版本? 我在想可能有一个JS / jQuery解决方案,但我仍然对这些基本了解,而我的搜索却很少。 我尝试了CSS动画延迟,但这并不是很理想,因为它取决于实际的时间,而不是何时加载图像。

我愿意接受其他建议。 任何帮助是极大的赞赏。

这是一个演示HTML和CSS 的JSFiddle ,下面还有一个嵌入式示例。

 .bg-wrapper {width: 500px; height: 250px; background: url(https://unsplash.it/2000/1000); background-position: 50% 0%; background-size: cover;} .bg {width: 100%; height: 100%; background: #FF4136; background: rgba(255,65,54,0.9)} 
 <div class="bg-wrapper"> <div class="bg"> </div> </div> 

是的,将不透明的背景移到一个单独的类,然后使用JS,创建一个新的Image() ,将图像URL分配为src并在该图像上使用onload事件将不透明的类添加到您的.bg元素中。

如果要淡化不透明度更改,请在.bg而不是rgba()上使用opacity ,并转换opacity属性。

 var img = new Image(); img.onload = function() { document.getElementsByClassName('bg')[0].classList.add('opaque'); } img.src = 'https://unsplash.it/1000/500?image=763'; 
 .bg-wrapper { width: 500px; height: 250px; background: url(https://unsplash.it/1000/500?image=763); } .bg { width: 100%; height: 100%; background: #FF4136; opacity: 1; transition: opacity .5s; } .opaque { opacity: .9 } 
 <div class="bg-wrapper"> <div class="bg"> </div> </div> 

您可能会喜欢使用伪元素和图像加载事件,它会从更新的CSS规则读取图像路径,从而定位元素数组

 (function(el){ el.forEach(function(e) { var style = e.currentStyle || window.getComputedStyle(e, false), bi = style.backgroundImage.slice(4, -1).replace(/["|']/g, ""); var img = new Image(); img.onload = function() { e.classList.add('loaded'); } img.src = bi; }); })(document.querySelectorAll('.bg-wrapper')); 
 .bg-wrapper { position: relative; width: 500px; height: 150px; background: url(http://lorempixel.com/500/200/nature/1/); background-position: 50% 0%; background-size: cover; } .bg-wrapper.nr2 { background: url(http://lorempixel.com/500/200/nature/2/); } .bg-wrapper::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: white; opacity: 1; transition: opacity 2s; } .bg-wrapper.loaded::before { opacity: 0.9; } .bg-wrapper * { position: relative; /* this make content stay ontop */ } 
 <div class="bg-wrapper"> <div> This is content..... </div> </div> <div class="bg-wrapper nr2"> <div> This is content..... </div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM