現象:父 div 無高度,無法包裹浮動子元素。
方案對比:
| 方法 | 代碼 | 優/缺點 |
|---|---|---|
額外標籤 clear:both | <div class="clear"></div> | 語義化差,增加無意義標籤 |
父級 overflow:auto/hidden | .parent{overflow:auto; _height:1%;} | 簡潔,但可能裁切內容/滾動條 |
| :after 偽元素(推薦) | 見下方 .clearfix | 語義化、無額外標籤、兼容性佳 |
父級 display:flow-root | .parent{display:flow-root;} | 現代瀏覽器原生支援,IE 不支援 |
萬能 Clearfix(支援 IE6+):
.clearfix:after {
content: "."; display: block; height: 0; clear: both; visibility: hidden;
}
.clearfix { *zoom: 1; } /* IE6/7 觸發 hasLayout */
.ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis; /* IE6+, Chrome, Safari, Opera, Firefox 7+ */
/* Firefox 早期版本不支援,需 JS 方案或接受降級 */
}
cursor: hand vs pointerhand 僅 IE 支援。pointer,全瀏覽器兼容。.transparent {
filter: alpha(opacity=60); /* IE 8- */
-moz-opacity: 0.6; /* 老 Firefox */
-khtml-opacity: 0.6; /* 老 Safari */
opacity: 0.6; /* 標準:IE9+, FF, Chrome, Safari, Opera */
}
width 與 padding 盒模型差異width = content 寬度,padding 向外擴展。width 包含 padding。box-sizing: border-box;(IE8+),或避免同時設 width 和 padding,改用內層元素承擔 padding。<meta http-equiv="X-UA-Compatible" content="IE=edge"> /* 強制最新模式,避免兼容模式 */
children vs childNodeschildren:僅返回元素節點(IE 早期專有,現為標準)。childNodes:返回所有節點(含文本節點、換行空白)。FF/Chrome 會包含換行文本節點,IE childNodes 行為與 children 一致(歷史原因)。element.children(現代瀏覽器均支援)或 Array.from(element.childNodes).filter(n => n.nodeType === 1)。event 獲取差異function handler(e) {
e = e || window.event; // IE 用 window.event
var target = e.target || e.srcElement; // 目標元素
var keyCode = e.keyCode || e.which; // 按鍵碼
// 阻止預設
if (e.preventDefault) e.preventDefault(); else e.returnValue = false;
// 阻止冒泡
if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true;
}
getComputedStyle vs currentStylefunction getStyle(el, prop) {
if (window.getComputedStyle) {
return getComputedStyle(el, null)[prop];
} else {
return el.currentStyle[prop]; // IE8-
}
}
addEventListener vs attachEventfunction on(el, type, fn) {
if (el.addEventListener) {
el.addEventListener(type, fn, false);
} else {
el.attachEvent('on' + type, fn); // IE8-
}
}
function off(el, type, fn) {
if (el.removeEventListener) {
el.removeEventListener(type, fn, false);
} else {
el.detachEvent('on' + type, fn);
}
}
innerText vs textContentinnerText:IE 專有,現已被標準納入,但行為有差異(受 CSS 影響、不返回隱藏元素文本)。textContent:標準,返回所有文本,速度更快。var text = el.textContent || el.innerText || '';document.all、document.layers 等古董檢測已棄用,現代代碼無需判斷,直接使用標準 API(document.getElementById, querySelectorAll 等)。
browserslist 配置。core-js、whatwg-fetch 等,配合 @babel/preset-env 自動按目標環境注入。'fetch' in window 而非 navigator.userAgent。