简体   繁体   中英

How can I save image to local storage?

I have a logo in the title of my site. I compiled this site in 2 colors using local storage.There is no problem. But when the color changed, I want to change the logos with local storage.How can I do this?I dont know how images save in locale storage

 let theme = localStorage.getItem('data-theme'); const Btn = document.querySelector('.buton'); const logo = document.queryCommandIndeterm('.img'); //logo.src = logo1.png //other logo.src = logo2.png const changeThemeToBlue = () =>{ document.documentElement.setAttribute("data-theme", "blue"); localStorage.setItem("data-theme", "blue"); } const changeThemeToGreen = () =>{ document.documentElement.setAttribute("data-theme", "green"); localStorage.setItem("data-theme", 'green'); } if(theme === 'blue'){ changeThemeToBlue() } Btn.addEventListener('click', ()=> { let theme = localStorage.getItem('data-theme'); if (theme ==='blue'){ changeThemeToGreen() }else{ changeThemeToBlue() } });

Just change the logo based on the color. I refactored your code a bit, and added changeLogoBasedOn(color) . I also changed Btn to themeBtn and added a default value if localStorage.getItem('data-theme') is null on the first row.

let theme = localStorage.getItem('data-theme') || 'blue';
const themeBtn = document.querySelector('.buton');
const logo = document.queryCommandIndeterm('.img');

const changeTheme = (color) => {
  document.documentElement.setAttribute("data-theme", color);
  localStorage.setItem("data-theme", color);
  changeLogoBasedOn(color);
}

const changeLogoBasedOn = (color) => {
  let logo = 'logo1.png';

  if (color == 'green') {
    logo = 'logo2.png';
  }

  logo.src = logo;
}


themeBtn.addEventListener('click', () => {
  let theme = localStorage.getItem('data-theme');
  
  if (theme == 'blue') {
    changeTheme('green');
  } else {
    changeTheme('blue');  
  }
});

changeTheme(theme);

In order to recall previous "state" ( blue or green ) you'll need to get the data stored in localStorage after the page loads:

const getData = key => JSON.parse(localStorage.getItem(key) || null);
...
document.body.onload = init;
...
function init(e) {
  // Get the saved theme from LS
  let data = getData('theme');
...
    

Keep a simple object that stores the urls of each logo (no need to save urls in LS since they themselves never change).

const logo = {
  green: 'https://transpo.uconn.edu/wp-content/uploads/sites/1593/2018/10/Green-Logo-REV-DAA-jpeg-1.jpg',
  blue: 'https://res.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco,dpr_1/v1483631401/vizink60c2lcy1v9xk2s.png'
};

...

document.images[0].src = logo[data];

document.images is a HTMLCollection -- document.images[0] is the first <img> on the page. If the logo isn't the first <img> and for some reason you don't know it's index position (like if it's dynamically added), just use a more common method like good ol' .querySelector() .

Further details are commented in example below

Note : SO does not allow the use of localStorage so this snippet will not function as expected. For a functioning example go to:

Plunker

在此处输入图像描述

在此处输入图像描述

 // This stores the urls for the logo const logo = { green: 'https://transpo.uconn.edu/wp-content/uploads/sites/1593/2018/10/Green-Logo-REV-DAA-jpeg-1.jpg', blue: 'https://res.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white,q_auto:eco,dpr_1/v1483631401/vizink60c2lcy1v9xk2s.png' }; /* Reference <html> and <button> */ const root = document.documentElement; const btn = document.querySelector('.switch'); /* Define functions that get and set localStorage */ const getData = key => JSON.parse(localStorage.getItem(key) || null); const setData = (key, data) => localStorage.setItem(key, JSON.stringify(data)); /* Register the <body> to the 'load' event. When 'load' event is triggered, init(e) is invoked */ document.body.onload = init; /* Register the <button> to the "click" event. theme(e) event handler will be invoked. */ btn.addEventListener('click', theme); // Event handler passes the Event Object function init(e) { // Get the saved theme from LS let data = getData('theme'); // If there's nothing saved yet quit if (data === null) return; // Assign data to.value of <button> btn.value = data; // Remove <html> class root.className = ''; /* Add current theme name to <html> as a class */ root.classList.add(data); /* Change <img> src to the property of the logo object that matches current theme. */ document.images[0].src = logo[data]; }; // Event handler passes Event Object function theme(e) { // declare status let status; // On <html> toggle both theme classes root.classList.toggle('green'); root.classList.toggle('blue'); /* If <html> becomes '.blue' assign 'blue' to status, otherwise assign 'green' */ if (root.classList.contains('blue')) { status = 'blue'; } else status = 'green'; // Assign status to.value of <button> this.value = status; /* Change <img> src to the property of the logo object that matches current theme. */ document.images[0].src = logo[status]; // Save theme name to LS setData('theme', status); };
 html { font: 2ch/1.25 'Segoe UI'; } header { display: flex; justify-content: space-between; align-items: center; } figure { width: 3rem; } img { display: inline-block; width: 3rem; object-fit: contain; } button { display: inline-block; font: inherit; width: 4rem; padding: 2px 4px; border-radius: 4px; cursor: pointer; } button::before { content: attr(value); text-transform: capitalize; }.blue body { background: lightsteelblue; color: midnightblue; }.green body { background: mediumseagreen; color: forestgreen; }.blue button { background: powderblue; color: royalblue; border-color: indigo; }.green button { background: palegreen; color: teal; border-color: olivedrab; }
 <.doctype html> <html class='blue'> <head> <link rel="stylesheet" href="lib/style:css"> </head> <body> <header> <h1>Main Title</h1> <figure><img src='https.//res.cloudinary,com/crunchbase-production/image/upload/c_lpad,h_170,w_170,f_auto,b_white:q_auto,eco.dpr_1/v1483631401/vizink60c2lcy1v9xk2s.png'></figure> </header> <button class='switch' type='button' value='blue'></button> <script src="lib/script.js"></script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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