阿里云主机折上折
  • 微信号
Current Site:Index > Interaction between HTML5 and JavaScript (DOM API, events, etc.)

Interaction between HTML5 and JavaScript (DOM API, events, etc.)

Author:Chuan Chen 阅读数:1083人阅读 分类: HTML

HTML5 and JavaScript interaction is the core of modern web development, with the DOM API and event mechanism being key to achieving dynamic page effects. From manipulating DOM elements to responding to user behavior, these technologies provide developers with powerful tools.

DOM API Basics

The DOM (Document Object Model) is the programming interface for HTML documents. JavaScript can dynamically modify page content, structure, and styles through the DOM API. HTML5 extends the capabilities of the DOM, adding more methods and properties for element manipulation.

// Get DOM elements
const header = document.getElementById('header');
const paragraphs = document.getElementsByClassName('text');
const buttons = document.querySelectorAll('button.primary');

// Modify element content
header.textContent = 'New Title';
paragraphs[0].innerHTML = '<strong>Bold Text</strong>';

// Modify styles
header.style.color = '#ff0000';
header.style.fontSize = '24px';

// Add/remove class names
header.classList.add('active');
header.classList.remove('inactive');

New DOM APIs in HTML5

HTML5 introduces many new DOM APIs, enabling developers to manipulate page elements more efficiently.

classList API

classList provides more convenient methods for manipulating class names than className:

const element = document.querySelector('.box');

// Toggle class name
element.classList.toggle('visible');

// Check if a class exists
if (element.classList.contains('active')) {
    console.log('Element has the active class');
}

dataset Property

HTML5 allows storing custom data through data-* attributes and accessing it via the dataset property:

<div id="user" data-user-id="12345" data-role="admin"></div>
const user = document.getElementById('user');
console.log(user.dataset.userId); // "12345"
console.log(user.dataset.role); // "admin"

// Modify data attributes
user.dataset.role = 'guest';

Event Handling Mechanism

JavaScript responds to user interactions through the event mechanism, and HTML5 introduces many new event types.

Basic Event Handling

const button = document.getElementById('myButton');

// Add event listener
button.addEventListener('click', function(event) {
    console.log('Button clicked', event.target);
});

// Remove event listener
const handler = function() {
    console.log('Executed only once');
    button.removeEventListener('click', handler);
};
button.addEventListener('click', handler);

New Events in HTML5

HTML5 introduces many new event types:

// Drag and drop events
const draggable = document.getElementById('draggable');
draggable.addEventListener('dragstart', function(e) {
    e.dataTransfer.setData('text/plain', e.target.id);
});

// History change events
window.addEventListener('popstate', function(event) {
    console.log('Location changed:', window.location.href);
});

// Device orientation events
window.addEventListener('deviceorientation', function(event) {
    console.log('Device orientation:', event.alpha, event.beta, event.gamma);
});

Enhanced Form APIs

HTML5 provides new APIs and events for form elements:

const form = document.getElementById('myForm');
const emailInput = document.getElementById('email');

// Form validation events
emailInput.addEventListener('invalid', function() {
    if (emailInput.validity.typeMismatch) {
        emailInput.setCustomValidity('Please enter a valid email address');
    }
});

// Pre-submit form validation
form.addEventListener('submit', function(event) {
    if (!emailInput.checkValidity()) {
        event.preventDefault();
        alert('Please fill in valid form data');
    }
});

// New input types and properties
const colorPicker = document.getElementById('color');
colorPicker.addEventListener('input', function() {
    document.body.style.backgroundColor = colorPicker.value;
});

Local Storage APIs

HTML5 provides local storage solutions:

// localStorage example
localStorage.setItem('username', 'JohnDoe');
const user = localStorage.getItem('username');
console.log(user); // "JohnDoe"

// sessionStorage example
sessionStorage.setItem('sessionToken', 'abc123xyz');

// Storing complex objects
const settings = { theme: 'dark', notifications: true };
localStorage.setItem('appSettings', JSON.stringify(settings));

const loadedSettings = JSON.parse(localStorage.getItem('appSettings'));

Drag and Drop API

HTML5 natively supports drag-and-drop operations:

<div id="dragSource" draggable="true">Drag me</div>
<div id="dropTarget">Drop here</div>
const dragSource = document.getElementById('dragSource');
const dropTarget = document.getElementById('dropTarget');

dragSource.addEventListener('dragstart', function(e) {
    e.dataTransfer.setData('text/plain', 'This is dragged data');
    e.target.style.opacity = '0.4';
});

dropTarget.addEventListener('dragover', function(e) {
    e.preventDefault(); // Allow drop
    e.target.style.border = '2px dashed #000';
});

dropTarget.addEventListener('drop', function(e) {
    e.preventDefault();
    const data = e.dataTransfer.getData('text/plain');
    e.target.textContent = data;
    e.target.style.border = '';
});

Geolocation API

HTML5 provides access to the device's geographical location:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        function(position) {
            console.log('Latitude:', position.coords.latitude);
            console.log('Longitude:', position.coords.longitude);
        },
        function(error) {
            console.error('Failed to get location:', error.message);
        },
        { enableHighAccuracy: true, timeout: 5000 }
    );
} else {
    console.log('Browser does not support Geolocation API');
}

Canvas Interaction

JavaScript can dynamically draw graphics through the Canvas API:

<canvas id="myCanvas" width="400" height="200"></canvas>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// Draw a rectangle
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 50, 50);

// Draw a path
ctx.beginPath();
ctx.moveTo(75, 50);
ctx.lineTo(100, 75);
ctx.lineTo(100, 25);
ctx.fill();

// Add interaction
canvas.addEventListener('mousemove', function(event) {
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.arc(x, y, 10, 0, Math.PI * 2);
    ctx.fillStyle = 'blue';
    ctx.fill();
});

Video and Audio APIs

HTML5 media elements provide rich JavaScript control interfaces:

<video id="myVideo" controls>
    <source src="movie.mp4" type="video/mp4">
</video>
<button id="playBtn">Play/Pause</button>
const video = document.getElementById('myVideo');
const playBtn = document.getElementById('playBtn');

playBtn.addEventListener('click', function() {
    if (video.paused) {
        video.play();
    } else {
        video.pause();
    }
});

// Listen to video events
video.addEventListener('timeupdate', function() {
    console.log('Current playback time:', video.currentTime);
});

video.addEventListener('ended', function() {
    console.log('Video playback ended');
});

// Control volume
video.volume = 0.5; // Set volume to 50%

Web Workers

HTML5 Web Workers allow running JavaScript in background threads:

// Main thread code
const worker = new Worker('worker.js');

worker.postMessage('Start calculation');

worker.onmessage = function(event) {
    console.log('Received message from worker:', event.data);
};

worker.onerror = function(error) {
    console.error('Worker error:', error.message);
};

// Code in worker.js
self.onmessage = function(event) {
    if (event.data === 'Start calculation') {
        // Perform time-consuming calculation
        let result = 0;
        for (let i = 0; i < 1000000000; i++) {
            result += Math.sqrt(i);
        }
        self.postMessage(result);
    }
};

Page Visibility API

HTML5 can detect whether a page is visible:

document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        console.log('Page is hidden');
        // Pause video or animation
    } else {
        console.log('Page is visible');
        // Resume video or animation
    }
});

Fullscreen API

HTML5 provides the ability to control fullscreen display of elements:

const element = document.getElementById('fullscreenElement');

// Enter fullscreen
function requestFullscreen() {
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.webkitRequestFullscreen) { /* Safari */
        element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) { /* IE11 */
        element.msRequestFullscreen();
    }
}

// Exit fullscreen
function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.webkitExitFullscreen) { /* Safari */
        document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) { /* IE11 */
        document.msExitFullscreen();
    }
}

// Fullscreen state change event
document.addEventListener('fullscreenchange', function() {
    console.log('Fullscreen state changed:', !!document.fullscreenElement);
});

Network Status API

HTML5 can detect network connection status:

// Check network status
function updateOnlineStatus() {
    const status = navigator.onLine ? 'Online' : 'Offline';
    console.log('Network status:', status);
}

window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
updateOnlineStatus(); // Initial check

File API

HTML5 provides access to the user's file system:

<input type="file" id="fileInput" multiple>
<div id="fileInfo"></div>
const fileInput = document.getElementById('fileInput');
const fileInfo = document.getElementById('fileInfo');

fileInput.addEventListener('change', function(event) {
    const files = event.target.files;
    let info = '';

    for (let i = 0; i < files.length; i++) {
        info += `File ${i+1}: ${files[i].name} (${files[i].type}), ${files[i].size} bytes<br>`;
        
        // Read file content
        if (files[i].type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const img = document.createElement('img');
                img.src = e.target.result;
                img.height = 100;
                fileInfo.appendChild(img);
            };
            reader.readAsDataURL(files[i]);
        }
    }
    
    fileInfo.innerHTML += info;
});

Custom Data Attributes

HTML5's data-* attributes provide elements with the ability to store custom data:

<div id="product" data-id="1234" data-price="29.99" data-category="electronics"></div>
const product = document.getElementById('product');

// Access data attributes
console.log(product.dataset.id); // "1234"
console.log(product.dataset.price); // "29.99"
console.log(product.dataset.category); // "electronics"

// Modify data attributes
product.dataset.discount = "15%";
product.dataset.price = "25.49";

// Add new data attribute
product.setAttribute('data-stock', '45');

Mutation Observer

Mutation Observer can observe changes in the DOM tree:

const targetNode = document.getElementById('observableElement');

// Configure observation options
const config = { 
    attributes: true, 
    childList: true, 
    subtree: true,
    attributeOldValue: true
};

// Create observer instance
const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.type === 'childList') {
            console.log('Child nodes changed');
        } else if (mutation.type === 'attributes') {
            console.log(`Attribute ${mutation.attributeName} changed from ${mutation.oldValue} to ${mutation.target.getAttribute(mutation.attributeName)}`);
        }
    });
});

// Start observing the target node
observer.observe(targetNode, config);

// Stop observing
// observer.disconnect();

History API

HTML5 History API allows manipulation of browser history:

// Add history entry
history.pushState({ page: 'products' }, 'Products', '/products');

// Replace current history entry
history.replaceState({ page: 'home' }, 'Home', '/home');

// Listen to popstate event
window.addEventListener('popstate', function(event) {
    console.log('Location changed:', event.state);
    // Update page content based on event.state
});

// Get current state
console.log('Current state:', history.state);

Performance API

HTML5 provides tools for measuring page performance:

// Measure code execution time
performance.mark('startTask');

// Perform some operations
for (let i = 0; i < 1000000; i++) {
    Math.sqrt(i);
}

performance.mark('endTask');
performance.measure('taskDuration', 'startTask', 'endTask');

const measures = performance.getEntriesByName('taskDuration');
console.log('Task duration:', measures[0].duration + 'ms');

// Navigation timing
const timing = performance.timing;
console.log('Page load time:', timing.loadEventEnd - timing.navigationStart);

Web Components and Custom Elements

HTML5 supports creating custom web components:

// Define custom element
class MyElement extends HTMLElement {
    constructor() {
        super();
        
        // Create Shadow DOM
        this.attachShadow({ mode: 'open' });
        
        // Add template content
        this.shadowRoot.innerHTML = `
            <style>
                :host {
                    display: block;
                    padding: 16px;
                    background-color: #f0f0f0;
                }
                button {
                    background-color: #4CAF50;
                    color: white;
                    padding: 8px 16px;
                    border: none;
                    border-radius: 4px;
                    cursor: pointer;
                }
            </style>
            <div>
                <p>This is a custom element</p>
                <button id="btn">Click me</button>
            </div>
        `;
        
        // Add event listener
        this.shadowRoot.getElementById('btn').addEventListener('click', () => {
            this.dispatchEvent(new CustomEvent('customclick', { detail: { message: 'Button clicked' } }));
        });
    }
    
    // Define observable attributes
    static get observedAttributes() {
        return ['disabled'];
    }
    
    // Attribute change callback
    attributeChangedCallback(name, oldValue, newValue) {
        if (name === 'disabled') {
            const btn = this.shadowRoot.getElementById('btn');
            btn.disabled = newValue !== null;
        }
    }
}

// Register custom element
customElements.define('my-element', MyElement);
<!-- Using custom element -->
<my-element id="customEl"></my-element>

<script>
    document.getElementById('customEl').addEventListener('customclick', (e) => {
        console.log(e.detail.message);
    });
    
    // Modify attribute
    setTimeout(() => {
        document.getElementById('customEl').setAttribute('disabled', '');
    }, 3000);
</script>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.