📜  javascript css - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:04.888000             🧑  作者: Mango

JavaScript and CSS

JavaScript and CSS are two of the most important tools for front-end web development. By combining these two technologies, developers can create dynamic and engaging web experiences.

JavaScript

JavaScript is a high-level programming language that is used to create interactive web pages. It is primarily used for client-side scripting, which means that it runs in the web browser of the user. JavaScript can be used for a wide variety of purposes, such as creating animations, handling user input, and communicating with web servers.

Example JavaScript Code
// display an alert box
alert('Hello, world!');

// create a new array and display its contents
var myArray = [1, 2, 3];
console.log(myArray);

// add a new element to the array
myArray.push(4);
console.log(myArray);
CSS

CSS is a stylesheet language that is used to define the presentation of web pages. It is primarily used for formatting HTML documents, and can be used to add colors, fonts, layout, and other visual styles to web pages.

Example CSS Code
/* set the background color of the page */
body {
  background-color: #f0f0f0;
}

/* add a border to all images in the page */
img {
  border: 1px solid black;
}

/* set the font family and size of all paragraphs in the page */
p {
  font-family: Arial;
  font-size: 12pt;
}
Combining JavaScript and CSS

Combining JavaScript and CSS can help create more engaging and dynamic web experiences. For example, JavaScript can be used to create animations and dynamic effects, while CSS can be used to style those effects.

Example Code
<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript and CSS Example</title>
    <style>
      /* set the background color of the page */
      body {
        background-color: #f0f0f0;
      }
      /* set the size and position of the box */
      #box {
        width: 100px;
        height: 100px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
    <script>
      // get a reference to the box element
      var box = document.getElementById('box');

      // animate the box
      var position = 0;
      setInterval(function () {
        position += 10;
        box.style.left = position + 'px';
      }, 100);
    </script>
  </body>
</html>

In this example, JavaScript is used to animate a box element, while CSS is used to style the box and set its position on the page. The result is a dynamic and engaging web experience that combines the power of JavaScript and CSS.