【发布时间】:2018-02-25 00:32:41
【问题描述】:
我从 codepen.io 复制了this code,为我网站的背景图片添加了淡入淡出效果。
var bgImageArray = ["lonely.jpg", "uluwatu.jpg", "carezza-lake.jpg", "batu-bolong-temple.jpg"],
base = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/full-",
secs = 4;
bgImageArray.forEach(function(img){
new Image().src = base + img;
// caches images, avoiding white flash between background replacements
});
function backgroundSequence() {
window.clearTimeout();
var k = 0;
for (i = 0; i < bgImageArray.length; i++) {
setTimeout(function(){
document.documentElement.style.background = "url(" + base + bgImageArray[k] + ") no-repeat center center fixed";
document.documentElement.style.backgroundSize ="cover";
if ((k + 1) === bgImageArray.length) { setTimeout(function() { backgroundSequence() }, (secs * 1000))} else { k++; }
}, (secs * 1000) * i)
}
}
backgroundSequence();
* {
box-sizing: border-box;
}
html {
margin: 0;
background-size: cover;
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/full-lonely.jpg") no-repeat center center fixed;
background-blend-mode: darken;
// blend mode optional at this stage; will be used more in the next demo.
transition: 3s;
}
body { margin: 0; }
div#texttop {
color: #fff;
width: 30%;
margin-top: 5%;
margin-left: 5%;
padding: 2rem;
border: 4px double rgba(255,255,255,0.3);
background: rgba(0,0,0,0.3);
font-family: Oxygen, sans-serif;
h1 {
margin-top: 0;
text-align: center;
font-weight: 100;
}
p {
line-height: 1.6;
}
}
@media all and (max-width: 770px) {
div#texttop { display: none; }
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="texttop">
<h1>True Cross-Fade Background Images</h1>
<p>A repeating sequence of fullscreen background images, pushed all the way to the root element. Crossfading effect in Webkit-derived browsers (Chrome, Safari, Opera).</p>
</div>
图像循环正常,但它们没有进行交叉淡入淡出过渡,它们只是在没有交叉淡入淡出效果的情况下发生变化。并且在图像循环之间偶尔会出现白色闪烁。
我已在此处插入了代码的 sn-p,但它仍然无法正常工作。也许有什么我找不到的东西丢失了?
【问题讨论】:
-
你用哪个浏览器试过这个...如果我记得,不是所有浏览器都支持
background-image中的转换 -
由于您的代码无法在 FF、IE 和 Edge 中运行...这里有一个建议:stackoverflow.com/a/25800332/383904 带有很好的图形解释
-
@RokoC.Buljan 谢谢你,我会试试的!
-
@unilogue 不客气,只是,答案有点老了,你可以使用
.addClass,removeClass,而不是 jQuery 的fade,让 CSS3transition来做而是淡化工作。快乐编码 -
@RokoC.Buljan 我最终使用了您的代码,而不是来自 codepen 的代码,它在所有浏览器中都能完美运行! thepeoplesday.org
标签: javascript jquery html css