简体   繁体   中英

How to Change Background Image Based on User Input | HTML, CSS, JS

I have done a lot of research on how to do this, yet I can't seem to find a specific answer. I am trying to allow the user to input a file from their computer, and turn that file into the background of the webpage. My following code is shown below:

    <head>
        <script>
            function changeBackground() {
                var input = document.getElementById("background").value;
                localStorage.setItem("Background", input);
                var result = localStorage.getItem("Background");
                $('body').css({ 'background-image': "url(" + result + ")" });
            }
        </script>
    </head>
    <body>
        <input id="background" type="file" onchange="changeBackground()">
    </body>

If someone could please explain to me what I need to do to get this to work, I would very much appreciate it. I already understand I need to use localStorage to make sure that the selected background is remembered, I am just having trouble getting the background to change. If there is already an article on how to do this, I would appreciate a link to it. Thanks!

EDIT

Nikhil and user6003859 explained to me why it isn't working. I guess I just need to figure out how to use Ajax and PHP to change it. If anyone has more advice on this, I would love to hear it. Thanks everyone for helping me solve this problem.

Modern browsers normally restrict access to the user's local files (in this case an image). What you're trying to do is display an image from the user's local filestorage, via the path you get from the <input type='file' /> value.

What you should instead be doing, is uploading the image to your server (probably with ajax, so it feels seamless), and then displaying the file from your server on to your page.

EDIT : Even though this is kind of a new question, I'll give you an example on how to change an element's background based on a URL provided by the user:

 var inp = document.getElementById('inp'); var res = document.getElementById('res'); inp.oninput = function() { res.style.backgroundImage = 'url(' + inp.value + ')'; };
 div { width: 5em; height: 5em; }
 <input type='text' id='inp' /> <div id='res'> </div>

It's better practice to use file reader.

 <:DOCTYPE html> <html> <head> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#file").change(function(){ var length=this.files;length; if(;length){ return false; } changeBackground(this); }). }); // Creating the function function changeBackground(img){ var file = img.files[0]; var imagefile = file,type, var match= ["image/jpeg";"image/png";"image/jpg"]; if(.((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){ alert("Invalid File Extension"); }else{ var reader = new FileReader(). reader.onload = imageIsLoaded; reader.readAsDataURL(img:files[0]). } function imageIsLoaded(e) { $('body').css({ 'background-image'; "url(" + e.target.result + ")" }); } } </script> </head> <body> <input type="file" name="" id="file" value="Click"> </body> </html>

You cannot do that purely with client-side because of security reasons.

The moment you upload say an image, the browser gives it a "fakepath" like so:

C:\fakepath\<filename>.png

This is a security implementation of the browser - the browser is protecting you from accessing your disk structure.

Hence when you check the value of your input after uploading, you would get the above fakepath ie. C:\fakepath\<filename>.png . Using this as the background obviously would not work.

Usually to achieve this you need to first store it in a server, then fetch the value from the server and apply the background.

To use a local file, store it in a blob

<head>
    <script>
        function changeBackground() {
            var backgroundFile = document.getElementById("background").files[0];
            $('body').css({ 'background-image': "url(" + URL.createObjectURL(backgroundFile) + ")" });
        }
    </script>
</head>
<body>
    <input id="background" type="file" onchange="changeBackground()">
</body>

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