JavaScript 是一種多用途的編程語言,廣泛應用於網頁開發和其他領域。
以下是 JavaScript 的一些主要實際用途和應用:
用戶界面交互:如彈出對話框、滑動效果、動態內容更新等。
document.getElementById('button').addEventListener('click', function() {
alert('Button clicked!');
});
動畫:使用 JavaScript 控制動畫效果,如圖片滑動、元素漸變等。
let element = document.getElementById('animatedElement');
let position = 0;
function move() {
position += 1;
element.style.left = position + 'px';
if (position < 200) {
requestAnimationFrame(move);
}
}
move();
function validateForm() {
let name = document.getElementById('name').value;
if (name === '') {
alert('Name cannot be empty');
return false;
}
return true;
}
document.getElementById('form').addEventListener('submit', validateForm);
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// Example with React
function App() {
return (
<div>
<h1>Hello, world!</h1>
</div>
);
}
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
// Main process (main.js)
const { app, BrowserWindow } = require('electron');
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
win.loadFile('index.html');
}
app.whenReady().then(createWindow);
// Example with React Native
import React from 'react';
import { Text, View } from 'react-native';
function App() {
return (
<View>
<Text>Hello, world!</Text>
</View>
);
}
export default App;
// Example with Chart.js
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
// Example for a simple Chrome extension
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, { file: 'content.js' });
});
這些實際應用展示了 JavaScript 的靈活性和強大功能,不僅能用於網頁開發,還可以應用於伺服器端開發、桌面和移動應用開發等多種領域。