search
HomeWeb Front-endFront-end Q&AJavaScript uses if to change background color switching

JavaScript is a high-level programming language widely used in web development. Javascript can be used to change the style of a web page, including modifying the color, font, and style of elements. This article will introduce how to use the if statement of Javascript to switch the background color.

1. Preparation

Before using Javascript, you first need to introduce it into the HTML page. Usually, a <script> tag is added to the <head> tag of HTML to introduce the Javascript file. The sample code is as follows: </script>

<html>
  <head>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.js"></script>
    <script src="main.js"></script>
  </head>
  <body>
    <div id="app">
      <h1 id="Hello-world">Hello, world!</h1>
    </div>
  </body>
</html>

In addition, we also need a page element to display the background color. In this example, we select the body element as the background color display area. The HTML code is as follows:

<body>
  <div id="app">
    <h1 id="Hello-world">Hello, world!</h1>
  </div>
</body>

2. Javascript implements background color switching

After introducing Javascript into the HTML page, we can use Javascript to control the style of page elements. In this example, we can use Javascript to modify the background color of the body element. You can use an if statement to switch the background color.

The sample code is as follows:

var body = document.querySelector('body');
if (body.style.backgroundColor === 'white') {
  body.style.backgroundColor = 'black';
} else {
  body.style.backgroundColor = 'white';
}

Code analysis:

First, we use document.querySelector('body') to get the body element. This function returns a reference to an element, which can be manipulated using the body in code.

Then, we use the if statement to determine whether the current background color is white. If the current background color is white, set the background color to black; otherwise, set the background color to white.

3. Use the button to trigger the background color switching

Now, we have implemented the background color switching through the if statement of Javascript. However, if the user wants to switch the background color more conveniently, we can add a button to trigger the switching of the background color. This can be achieved by adding a button element contained in the HTML.

HTML sample code is as follows:

<button onclick="toggleBackground()">Click me!</button>

We added a button element and used the onclick attribute to specify the function toggleBackground() to be called when the button is clicked.

We need to add a function named toggleBackground(), the code is as follows:

function toggleBackground() {
  var body = document.querySelector('body');
  if (body.style.backgroundColor === 'white') {
    body.style.backgroundColor = 'black';
  } else {
    body.style.backgroundColor = 'white';
  }
}

This function is the same as the previous sample code, it uses an if statement to switch the background color. When the button is clicked, this function will be called and the background color will switch to another color.

4. Complete code implementation

The following is the complete HTML page code, which can be directly copied to the editor for use.

 

  
    
    
    <script>
      function toggleBackground() {
        var body = document.querySelector('body');
        if (body.style.backgroundColor === 'white') {
          body.style.backgroundColor = 'black';
        } else {
          body.style.backgroundColor = 'white';
        }
      }
    </script>
  
  
    <button onclick="toggleBackground()">Click me!</button>
    

Hello, world!

In the entire HTML file, we added a <script> tag containing the toggleBackground() function, and added a <button> element in the <body> tag to trigger the switching of the background color. . When the button is clicked, the toggleBackground() function will be called and the background color will switch to another color. </script>

This article introduces how to use Javascript’s if statement to switch the background color. At the same time, we also show you how to use the

The above is the detailed content of JavaScript uses if to change background color switching. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Benefits of React's Strong Community and EcosystemThe Benefits of React's Strong Community and EcosystemApr 29, 2025 am 12:46 AM

React'sstrongcommunityandecosystemoffernumerousbenefits:1)ImmediateaccesstosolutionsthroughplatformslikeStackOverflowandGitHub;2)Awealthoflibrariesandtools,suchasUIcomponentlibrarieslikeChakraUI,thatenhancedevelopmentefficiency;3)Diversestatemanageme

React Native for Mobile Development: Building Cross-Platform AppsReact Native for Mobile Development: Building Cross-Platform AppsApr 29, 2025 am 12:43 AM

ReactNativeischosenformobiledevelopmentbecauseitallowsdeveloperstowritecodeonceanddeployitonmultipleplatforms,reducingdevelopmenttimeandcosts.Itoffersnear-nativeperformance,athrivingcommunity,andleveragesexistingwebdevelopmentskills.KeytomasteringRea

Updating State Correctly with useState() in ReactUpdating State Correctly with useState() in ReactApr 29, 2025 am 12:42 AM

Correct update of useState() state in React requires understanding the details of state management. 1) Use functional updates to handle asynchronous updates. 2) Create a new state object or array to avoid directly modifying the state. 3) Use a single state object to manage complex forms. 4) Use anti-shake technology to optimize performance. These methods can help developers avoid common problems and write more robust React applications.

React's Component-Based Architecture: A Key to Scalable UI DevelopmentReact's Component-Based Architecture: A Key to Scalable UI DevelopmentApr 29, 2025 am 12:33 AM

React's componentized architecture makes scalable UI development efficient through modularity, reusability and maintainability. 1) Modularity allows the UI to be broken down into components that can be independently developed and tested; 2) Component reusability saves time and maintains consistency in different projects; 3) Maintainability makes problem positioning and updating easier, but components need to be avoided overcomplexity and deep nesting.

Declarative Programming with React: Simplifying UI LogicDeclarative Programming with React: Simplifying UI LogicApr 29, 2025 am 12:06 AM

In React, declarative programming simplifies UI logic by describing the desired state of the UI. 1) By defining the UI status, React will automatically handle DOM updates. 2) This method makes the code clearer and easier to maintain. 3) But attention should be paid to state management complexity and optimized re-rendering.

The Size of React's Ecosystem: Navigating a Complex LandscapeThe Size of React's Ecosystem: Navigating a Complex LandscapeApr 28, 2025 am 12:21 AM

TonavigateReact'scomplexecosystemeffectively,understandthetoolsandlibraries,recognizetheirstrengthsandweaknesses,andintegratethemtoenhancedevelopment.StartwithcoreReactconceptsanduseState,thengraduallyintroducemorecomplexsolutionslikeReduxorMobXasnee

How React Uses Keys to Identify List Items EfficientlyHow React Uses Keys to Identify List Items EfficientlyApr 28, 2025 am 12:20 AM

Reactuseskeystoefficientlyidentifylistitemsbyprovidingastableidentitytoeachelement.1)KeysallowReacttotrackchangesinlistswithoutre-renderingtheentirelist.2)Chooseuniqueandstablekeys,avoidingarrayindices.3)Correctkeyusagesignificantlyimprovesperformanc

Debugging Key-Related Issues in React: Identifying and Resolving ProblemsDebugging Key-Related Issues in React: Identifying and Resolving ProblemsApr 28, 2025 am 12:17 AM

KeysinReactarecrucialforoptimizingtherenderingprocessandmanagingdynamiclistseffectively.Tospotandfixkey-relatedissues:1)Adduniquekeystolistitemstoavoidwarningsandperformanceissues,2)Useuniqueidentifiersfromdatainsteadofindicesforstablekeys,3)Ensureke

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),