我想知道在将图像上传到本地存储后如何添加过渡(淡入淡出效果)?
$(switchBackground);
var oFReader = new FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function(oFREvent) {
localStorage.setItem('b', oFREvent.target.result);
switchBackground();
};
function switchBackground() {
var backgroundImage = localStorage.getItem('b');
if (backgroundImage) {
$('body').css('background-image', 'url(' + backgroundImage + ')');
}
}
function loadImageFile(testEl) {
if (!testEl.files.length) {
return;
}
var oFile = testEl.files[0];
if (!rFilter.test(oFile.type)) {
alert("You must select a valid image file!");
return;
}
oFReader.readAsDataURL(oFile);
}
<input id="test" type="file" onchange="loadImageFile(this)" />
答案 0 :(得分:0)
CSS background-image
属性没有内置的动画方法。
CSS伪元素可以设置动画。您可以使用:after
CSS伪元素,将width
设置为calc(100vw)
,将height
设置为calc(100vh)
以覆盖视口,并使用animation
属性设置keyframes
对应的伪元素content
属性值从opacity
0
到opacity
1
的动画位置。如果backgroundImage
不是null
,则将CSS文本附加到<style>
元素,该元素将content
伪元素的body
:after
伪元素的content
属性设置为{{1} }设置为CSS url()
函数,以将data URL
检索到的localStorage
。
<!DOCTYPE html>
<html>
<head>
<style>
body:after {
position: relative; /* set `position` to `relative`
content: unset; /* set `content` to `unset` */
width: calc(100vw); /* width of viewport */
height: calc(100vh); /* height of viewport */
animation: bg 5s ease forwards; /* `iteration-timing-function` set to `forwards` */
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(switchBackground);
var oFReader = new FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function(oFREvent) {
localStorage.setItem('b', oFREvent.target.result);
switchBackground();
};
function switchBackground() {
var backgroundImage = localStorage.getItem('b');
if (backgroundImage) {
// set `body:after` `content` to `data URL`: `backgroundImage`
$("style").append(`body:after{content:url(${backgroundImage})} @keyframes bg {from {opacity:0}to {opacity:1)}}`);
}
}
function loadImageFile(testEl) {
if (!testEl.files.length) {
return;
}
var oFile = testEl.files[0];
if (!rFilter.test(oFile.type)) {
alert("You must select a valid image file!");
return;
}
oFReader.readAsDataURL(oFile);
}
</script>
</head>
<body>
<input id="test" type="file" onchange="loadImageFile(this)" />
</body>
</html>