jquery changes background image

WBOY
Release: 2023-05-08 19:02:05
Original
900 people have browsed it

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;
}
Copy after login

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>
Copy after login

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');
Copy after login

To change the background image of the .container, you can use the following code:

var $container = $('.container');
Copy after login

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")');
Copy after login

To change the background image of the .container to bg4.png, you can use the following code:

$container.css('background-image', 'url("bg4.png")');
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template