3.根据天气状况动态更新其样式。
<template id="weather-widget-template"> <style> /* Styles for the widget */ </style> <slot name="title">Weather Forecast</slot> <select class="city-selector"> <!-- City options go here --> </select> <div class="weather-display"> <span class="temperature"></span> <span class="humidity"></span> <img class="weather-icon" alt="Weather Icon"> </div> <slot name="footer"></slot> </template>(2)JavaScript Logic
class WeatherWidget extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); const template = document.getElementById('weather-widget-template'); const node = document.importNode(template.content, true); this.shadowRoot.appendChild(node); this._citySelector = this.shadowRoot.querySelector('.city-selector'); this._weatherDisplay = this.shadowRoot.querySelector('.weather-display'); // Event listeners and other logic... } connectedCallback() { this._citySelector.addEventListener('change', this._fetchWeatherData.bind(this)); this._fetchWeatherData(); } _fetchWeatherData() { const city = this._citySelector.value; // Fetch the weather data for the city and update the widget... } } customElements.define('weather-widget', WeatherWidget);(3)获取天气数据
_fetchWeatherData() { const city = this._citySelector.value; fetch(`https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=${city}`) .then(response => response.json()) .then(data => { const { temp_c, humidity, condition } = data.current; this.shadowRoot.querySelector('.temperature').textContent = `${temp_c}°C`; this.shadowRoot.querySelector('.humidity').textContent = `Humidity: ${humidity}%`; this.shadowRoot.querySelector('.weather-icon').src = condition.icon; }); }(4)动态样式
// ... Inside the _fetchWeatherData function ... .then(data => { // ... Other data processing ... const widgetElement = this.shadowRoot.querySelector('.weather-display'); if (temp_c <= 0) { widgetElement.classList.add('cold-weather'); } else if (temp_c > 30) { widgetElement.classList.add('hot-weather'); } })
<weather-widget> <span slot="title">My Custom Weather Title</span> <span slot="footer">Weather data sourced from WeatherAPI</span> </weather-widget>