ユーザ入力から背景イメージを読み込むこのボタンをカスタマイズしようとしています。ユーザーが背景画像を追加した後、別の画像を追加する(つまり、2回目をクリック)をクリックすると、プロンプトが再表示されて別の画像を追加すると、最初の画像をバックグラウンドから削除します。htmlページの背景イメージを設定してクリアします
$(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() {
$('body').css('background-image', "url(" + localStorage.getItem('b') + ')');
}
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)" />
Here is a JS Fiddle of this code.
JS Fiddleで動作しますか?クリックすると、別のものを選択したかどうかに関係なく、背景イメージが削除されます。 – Shakespeare
はい。それをもう一度クリックします。 –