How can I let users customize background images?

て烟熏妆下的殇ゞ 提交于 2019-12-06 14:46:23

问题


Many sites these days have 'theming' functionality, when user is able to customize the pages' look. Sometimes it's only a fixed set of themes, but sometimes people are free to choose any style they want - for example, they can set up any color of the pages' background.

I want to go a step further - and let them choose the background image as well. The flow is very simple: user uploads a file (via <input type="file" />), then this file becomes a background image - but only for this user.

I can't find anything about this functionality online, though, and I have no clue about what to do.

Something else I was thinking was that, if a user selects a background, maybe I could use HTML5 localstorage to make that background come up every-time that visitor visits the page.


回答1:


Here's a proof of concept (mostly based on the code given at MDN FileReader doc page + this answer):

HTML:

<input id="test" type="file" onchange="loadImageFile(this)" />

JS: no wrap (head) mode

$(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);
}

And here's a working demo, checked in latest Firefox and Chrome versions. Looks to work OK, at least. )




回答2:


here's a quick solution to this problem.

custom-background.js is a lightweight jQuery plugin to allow users change the website’s default background and saves the background selected to local storage. This plugin can easily be added to any website or web app without any compromise on website's performance.

you can download it from here and check the code https://github.com/CybrSys/custom-background.js



来源:https://stackoverflow.com/questions/14678207/how-can-i-let-users-customize-background-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!