我正在嘗試制作一個允許我的用戶自定義我網站的整個背景的功能。所以我制作了一個圖片上傳表格,但我不知道接下來如何處理我從用戶那里獲得的這張圖片。此影像的存盤位置以及如何訪問此影像并將此影像作為背景影像。下面是我的html
<div class="crossfade">
<figure></figure>
<figure></figure>
<figure></figure>
<figure></figure>
<figure></figure>
</div>
我用css給了影片
.crossfade figure {
animation: imageAnimation 60s linear infinite 0s;
backface-visibility: hidden;
background-size: cover;
background-position: center;
color: transparent;
height: 100%;
width: 100%;
left: 0px;
opacity: 0;
position: absolute;
top: 0px;
z-index: -1;
margin: 0;
}
.crossfade > figure:nth-child(1) {
background-image: url(../img/0.jpeg);
}
.crossfade > figure:nth-child(2) {
animation-delay: 12s;
background-image: url(../img/1.jpeg);
}
.crossfade > figure:nth-child(3) {
animation-delay: 24s;
background-image: url(../img/2.jpeg);
}
.crossfade > figure:nth-child(4) {
animation-delay: 36s;
background-image: url(../img/0.jpeg);
}
.crossfade > figure:nth-child(5) {
animation-delay: 48s;
background-image: url(../img/1.jpeg);
}
@keyframes imageAnimation {
0% {
animation-timing-function: ease-in;
opacity: 0;
}
8% {
animation-timing-function: ease-out;
opacity: 1;
}
17% {
opacity: 1;
}
45% {
opacity: 0;
}
100% {
opacity: 0;
}
}
并通過表單從用戶那里獲取影像
<form id="background-form" method="get">
<div>
<label for="custom-file" class="form-label">Choose Images to upload(jpg, jpeg, or png) up to 5MB</label>
<input
required
type="file"
class="form-control"
id="custom-file"
accept=".jpg, .jpeg, .png"
multiple/>
</div>
</form>
和處理提交的javascript檔案
const submit = document.querySelector("form#background-form")
function handleSubmit() {
//How should I access to the image I got from form
//I tried to access by using URL.createObjectURL(file) API but didn't work
//Or is there a way to store this image in localstorage or sessionstorage?
//If it is possible how can I access to the image URL?
}
uj5u.com熱心網友回復:
有一種方法可以根據您的需要使用本地和會話存盤來存盤您的影像并進行計數,localStorage 的大小限制為 5mb,并且用戶可以在需要時增加限制,但是,只有少數瀏覽器支持這一點,但在其他手 sessionStorage 的大小僅受系統記憶體限制。
要將影像保存在 localStorage 中,您可以執行以下操作。
const fileInput = document.querySelector('#fileInput');
當輸入改變時 - 當影像被選擇或改變時,這個函式執行
fileInput.addEventListener('change', function () {
const reader = new FileReader(); -- read content of files
加載檔案內容時
reader.addEventListener('load', function () {
將結果(影像)保存在本地存盤中
localStorage.setItem('image', reader.result)
})
讀取 blob 或檔案的內容
reader.readAsDataURL(this.files[0]);
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/425175.html
標籤:javascript 形式 图片 文件
