HTML5 引入了許多新特性,主要包括:
<header>、<footer>、<article>、<section> 等,使得頁面結構更加清晰。<audio> 和 <video> 標簽,使得在網頁中嵌入音頻和視頻變得更加簡單。<input> 類型,如 email、date、range 等,以及表單驗證功能。localStorage 和 sessionStorage 提供了在客戶端存儲數據的能力。實例分析:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 新特性示例</title>
</head>
<body>
<header>
<h1>這是頁頭</h1>
</header>
<section>
<article>
<h2>文章標題</h2>
<p>文章內容...</p>
</article>
</section>
<footer>
<p>這是頁腳</p>
</footer>
</body>
</html>
CSS 盒模型是網頁布局的基礎,它由內容(content)、內邊距(padding)、邊框(border)和外邊距(margin)組成。
width 和 height 只包含內容區域。width 和 height 包含內容、內邊距和邊框。實例分析:
.box {
width: 200px;
height: 100px;
padding: 20px;
border: 10px solid black;
margin: 30px;
}
在標準盒模型中,.box 的實際寬度為 200px + 20px * 2 + 10px * 2 = 260px,而在 IE 盒模型中,寬度為 200px。
Flexbox 是一種一維布局模型,適用于在單行或單列中排列元素。
display: flex;、flex-direction、justify-content、align-items 等。flex-grow、flex-shrink、flex-basis 等。實例分析:
.container {
display: flex;
justify-content: space-between;
align-items: center;
}
.item {
flex: 1;
}
CSS 選擇器的優先級決定了哪個樣式規則會被應用。優先級從高到低依次為:
!important實例分析:
#id-selector {
color: red; /* 優先級最高 */
}
.class-selector {
color: blue;
}
div {
color: green;
}
BFC(Block Formatting Context)是塊級格式化上下文,它是一個獨立的渲染區域,內部的元素不會影響到外部的元素。
觸發 BFC 的條件:
float 不為 noneposition 為 absolute 或 fixeddisplay 為 inline-block、table-cell、table-caption、flex、inline-flexoverflow 不為 visible實例分析:
.container {
overflow: hidden; /* 觸發 BFC */
}
閉包是指函數能夠訪問其詞法作用域中的變量,即使函數在其詞法作用域之外執行。
實例分析:
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 輸出 1
counter(); // 輸出 2
JavaScript 中的每個對象都有一個原型對象,對象通過原型鏈繼承屬性和方法。
實例分析:
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
const person = new Person('Alice');
person.sayHello(); // 輸出 "Hello, my name is Alice"
JavaScript 是單線程的,通過事件循環機制處理異步任務。
實例分析:
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
Promise.resolve().then(() => {
console.log('Promise');
});
console.log('End');
輸出順序為:Start、End、Promise、Timeout。
Promise 是處理異步操作的對象,async/await 是基于 Promise 的語法糖。
實例分析:
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched');
}, 1000);
});
}
async function getData() {
const data = await fetchData();
console.log(data);
}
getData(); // 輸出 "Data fetched"
this 的指向取決于函數的調用方式。
實例分析:
const obj = {
name: 'Alice',
sayName: function() {
console.log(this.name);
}
};
obj.sayName(); // 輸出 "Alice"
const sayName = obj.sayName;
sayName(); // 輸出 undefined(非嚴格模式下為全局對象)
Vue 實例從創建到銷毀的整個過程稱為生命周期,主要包括以下鉤子函數:
beforeCreatecreatedbeforeMountmountedbeforeUpdateupdatedbeforeDestroydestroyed實例分析:
new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
beforeCreate() {
console.log('beforeCreate');
},
created() {
console.log('created');
},
beforeMount() {
console.log('beforeMount');
},
mounted() {
console.log('mounted');
}
});
Vue 通過 Object.defineProperty 實現數據的響應式。
實例分析:
const data = { message: 'Hello' };
Object.defineProperty(data, 'message', {
get() {
console.log('get message');
return this._message;
},
set(newValue) {
console.log('set message');
this._message = newValue;
}
});
data.message = 'World'; // 輸出 "set message"
console.log(data.message); // 輸出 "get message" 和 "World"
Vuex 是 Vue 的狀態管理庫,用于管理全局狀態。
實例分析:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
increment({ commit }) {
commit('increment');
}
}
});
new Vue({
el: '#app',
store,
computed: {
count() {
return this.$store.state.count;
}
},
methods: {
increment() {
this.$store.dispatch('increment');
}
}
});
Vue Router 是 Vue 的路由管理器,用于實現單頁應用的路由。
實例分析:
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = new VueRouter({
routes
});
new Vue({
el: '#app',
router
});
Vue 組件通信方式包括:
props 傳遞數據給子組件,子組件通過 $emit 觸發事件。實例分析:
// 父組件
Vue.component('parent', {
template: `
<div>
<child :message="message" @update="updateMessage"></child>
</div>
`,
data() {
return {
message: 'Hello'
};
},
methods: {
updateMessage(newMessage) {
this.message = newMessage;
}
}
});
// 子組件
Vue.component('child', {
props: ['message'],
template: `
<div>
<p>{{ message }}</p>
<button @click="changeMessage">Change Message</button>
</div>
`,
methods: {
changeMessage() {
this.$emit('update', 'World');
}
}
});
React 組件的生命周期主要包括以下階段:
constructor、render、componentDidMountshouldComponentUpdate、render、componentDidUpdatecomponentWillUnmount實例分析:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
React Hooks 是 React 16.8 引入的新特性,允許在函數組件中使用狀態和其他 React 特性。
實例分析:
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Component mounted or updated');
}, [count]);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Redux 是 React 的狀態管理庫,用于管理全局狀態。
實例分析:
import { createStore } from 'redux';
const initialState = { count: 0 };
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
}
const store = createStore(reducer);
store.dispatch({ type: 'INCREMENT' });
console.log(store.getState()); // 輸出 { count: 1 }
React Router 是 React 的路由管理器,用于實現單頁應用的路由。
實例分析:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function Home() {
return <h1>Home</h1>;
}
function About() {
return <h1>About</h1>;
}
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</Router>
);
}
React 組件通信方式包括:
props 傳遞數據給子組件,子組件通過回調函數傳遞數據給父組件。React.createContext 實現跨組件通信。實例分析:
// 父組件
function Parent() {
const [message, setMessage] = useState('Hello');
return (
<div>
<Child message={message} onChangeMessage={setMessage} />
</div>
);
}
// 子組件
function Child({ message, onChangeMessage }) {
return (
<div>
<p>{message}</p>
<button onClick={() => onChangeMessage('World')}>Change Message</button>
</div>
);
}
前端性能優化策略包括:
實例分析:
<!-- 使用 CDN 加載 jQuery -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
懶加載是延遲加載非關鍵資源,預加載是提前加載關鍵資源。
實例分析:
<!-- 懶加載圖片 -->
<img data-src="image.jpg" class="lazyload" />
<!-- 預加載關鍵資源 -->
<link rel="preload" href="critical.css" as="style" />
代碼分割是將代碼拆分成多個小塊,按需加載。Tree Shaking 是移除未使用的代碼。
實例分析:
// 使用動態導入實現代碼分割
import('lodash').then(({ default: _ }) => {
console.log(_.chunk([1, 2, 3, 4], 2));
});
合理使用緩存策略可以提升頁面加載速度。
**實例分析
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。