Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery - Background color change from dropdown using javascript

I would like to be able to change background colour by having to choose from drop down menu.

<div id="background">
                <p><b>Choose a colour to change<br> background colour from the list.</b></p>
                    <select name="colour" id="background-change">
                        <option>Select One</option>
                        <option>Black</option> 
                        <option>Blue</option>
                        <option>Orange</option> 
                        <option>Red</option>
                        <option>White</option>
                        <option>Yellow</option>
                    </select> 
</div>

Thats my HTML drop down code and the colours i need the background to change. Also I would like to have it save in the cookie so if i pick red and refresh the page, it would still be red.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a solution using jQuery

$(document).ready(function () {

//$("#background").css("background-color",$.cookie("defaultColor"));

    $("#background-change").change(function (event) {
      var color =  $(this).val();
       $("#background").css("background-color",color);

        //$.cookie("defaultColor",color);
    });
});

The code will change the background based on the selected value in the dropdown list.

To set and retrieve cookie using jQuery, you have to use the jQuery Cookie Plugin

Use this code to set cookie

$.cookie("defaultColor",color);

Then use this code to retrieve cookie and set it as the backround color

$("#background").css("background-color",$.cookie("defaultColor"));

Check the Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...