Home > Article > Web Front-end > jquery changes background image
In web development, changing the background image is a basic task. Using jQuery, you can achieve this task more easily. This article will introduce how to use jQuery to modify the page background image.
First, we need an HTML page and declare a CSS style sheet for it. In the style sheet, we can define one or more background images according to our needs. For example, the following is a basic CSS style sheet that defines two background images:
body { background-image: url("bg1.png"); background-repeat: repeat; } .container { background-image: url("bg2.png"); background-repeat: no-repeat; }
Next, we need to introduce the jQuery library. Add the following code to the HTML page:
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
Now, we can use jQuery code to modify the background image on the page. First, you need to get the element whose background image you want to change. We can use selectors in jQuery to get elements. For example, to change the background image of the body, you can use the following code:
var $body = $('body');
To change the background image of the .container, you can use the following code:
var $container = $('.container');
Next, use the css method in jQuery to modify the background image. The following code can change the background image of the body to bg3.png:
$body.css('background-image', 'url("bg3.png")');
To change the background image of the .container to bg4.png, you can use the following code:
$container.css('background-image', 'url("bg4.png")');
Need to pay attention to modification When using a background image, you need to provide the correct image path and set the format of the background image correctly.
If you need to add animation effects in time, you can use the animate method. For example, the following code will change the background image of the container from bg2.png to bg5.png in 2 seconds:
$container.animate({ 'background-image': 'url("bg5.png")' }, 2000);
The above is how to modify the background image using jQuery. Through simple jQuery code, we can more easily modify the background image of the web page. Hope this article will be helpful to you.
The above is the detailed content of jquery changes background image. For more information, please follow other related articles on the PHP Chinese website!