简体   繁体   中英

Change <div> background image with javascript

I've this in my html file

<div class="change">
            <div id="changed" onclick="change_DImage()">New Upload...</div>
            <input id="browse" type="file" onchange="ImagLoc()">
</div>

and this in javascript file

function change_DImage(){
          document.getElementById("browse").click();  
    }
function ImagLoc(){
          var x = (document.getElementById("browse").value).toString();
          var ImgId = x.substr(12,6);
          var NewImg = "url('./image/MyAlbum/" + ImgId + "')";
          document.getElementById("dailyPic").style.backgroundImage = NewImg;
}

it's work pretty well but when I refresh my browser it'll change back to the default

for this in css file

background-image: url("../image/smokebird.jpg");

Javascript manipulates the only current state of the Html, not the file on server side. To handle it, you have to store state on server side, and change it both client and server side on button click.

Storing changed value on browser's cookie or local storage, and get stored one on page load is another option.

On page reload obviously image is going to reset to the original image. To keep it as it is even after page refresh you can do,

  1. Save the image in Cookie (base 64 format), but there is a size limit since you can save small size images only.

  2. On image select, you can save the image file remotely on your server asynchronously (using AJAX) and you can recall the image using the server session.

localStorage example: jsfiddle


However localStorage can be easily cleaned by user, even by mistake. I have found this answer useful about how it can be cleaned: SO link . Other drawback (if your really care about it) is a need of use Inline styling. There is attr css function but other than content usage is currently limited so I would stick to Inline styling.
I made more understandable version including your code, here: jsfiddle , however I am not sure what this line and function suppose to do so I have removed it:

<div id="changed" onclick="change_DImage()">New Upload...</div>

Edit: obviously second jsfiddle code will not work on jsfiddle, you need to inject it to your code.

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