平滑地改变背景



在我的原始项目中,我有类似reNewIt((的相同函数,但只是在开始时使用了fadeIn((,并且在加载文档后调用它,fadeIn效果(从不透明度0到1(很好。

当我试图制作一个按钮来更改背景时(首先将不透明度设置为0,然后更改图像,然后将不透明度设为1(,我在开发工具中看到不透明度从1跳到0.98,但它不起作用。尝试了不同的解决方案,但我认为setInterval有一些我无法理解的地方。这个想法是首先变成全白色,然后更改img,以隐藏图片的加载时间

我整天都在看帖子和搜索谷歌,无法让它发挥作用。。我可以简单地获取一些其他代码来实现这种效果,但我真的想自己制作。(当我想学习时,复制有什么意义(如果有人能帮我弄清楚,我会很高兴的。

let images = {
img1: 'https://miro.medium.com/max/1200/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg',
img2: 'https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8ZGF3bnxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80',
img3: 'https://images.ctfassets.net/hrltx12pl8hq/4plHDVeTkWuFMihxQnzBSb/aea2f06d675c3d710d095306e377382f/shutterstock_554314555_copy.jpg',
img4: 'https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014__340.jpg'
}


function reNewIt() {
let opacity = 1;
let elem = document.getElementById('bgimage');
let num = Math.ceil(Math.random() * 4);
fadeOut();
elem.style.backgroundImage = `url(${images['img'+ num ]})`;
fadeIn();

function fadeIn() {
let id = 0;
id = setInterval(frameIn, 20);
function frameIn() {
opacity += 0.02;
elem.style.opacity = opacity;
}
}
function fadeOut() {
let id = 0;
id = setInterval(frameOut, 20);
function frameOut() {
opacity -= 0.02;
elem.style.opacity = opacity;
}
}
}
#bgimage {
opacity: 1;
height: 200px;
width: 1000px;
border: 1px solid red;
color:red;
}
<html>
<head>
</head>
<body>
<div id="bgimage">
<button onclick="reNewIt()">Click me</button>
</div>
</body>
</html>

您可以在css 中添加转换

let images = {
img1: 'https://miro.medium.com/max/1200/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg',
img2: 'https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8ZGF3bnxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80',
img3: 'https://images.ctfassets.net/hrltx12pl8hq/4plHDVeTkWuFMihxQnzBSb/aea2f06d675c3d710d095306e377382f/shutterstock_554314555_copy.jpg',
img4: 'https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014__340.jpg'
}


function reNewIt() {
let opacity = 1;
let elem = document.getElementById('bgimage');
let num = Math.ceil(Math.random() * 4);
fadeOut();
elem.style.backgroundImage = `url(${images['img'+ num ]})`;
fadeIn();

function fadeIn() {
let id = 0;
id = setInterval(frameIn, 20);
function frameIn() {
opacity += 0.02;
elem.style.opacity = opacity;
}
}
function fadeOut() {
let id = 0;
id = setInterval(frameOut, 20);
function frameOut() {
opacity -= 0.02;
elem.style.opacity = opacity;
}
}
}
#bgimage {
opacity: 1;
height: 200px;
width: 1000px;
border: 1px solid red;
color:red;
transition: 2s ease-out;
}
<html>
<head>
</head>
<body>
<div id="bgimage">
<button onclick="reNewIt()">Click me</button>
</div>
</body>
</html>

最新更新