我怎样才能让用户自定义背景图片? [英] How can I let users customize background images?

查看:291
本文介绍了我怎样才能让用户自定义背景图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多网站,这些天有主题化的功能,当用户能够定制网页的外观。有时,它只是主题的一组固定的,但有时人们可​​以自由选择他们想要的任何风格 - 例如,他们可以设置网页的背景颜色的任何

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.

别的东西,我在想是,如果用户选择的背景下,也许我可以使用HTML5 的localStorage 来作出这样的背景下提出了每一次的访问者访问了页。

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.

推荐答案

下面是一个概念验证(主要是基于在的 MDN的FileReader文档页面 + <一个href=\"http://stackoverflow.com/questions/9344526/setting-css-background-to-an-image-in-local-storage\">this答案):

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 无包(头)模式

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

和这里的 工作演示 ,在最新的Firefox和Chrome检查版本。看起来工作确定,至少。 )

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

这篇关于我怎样才能让用户自定义背景图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆