本文介紹瞭如何使用Bootstrap實現響應式佈局,如何定製自己的響應式框架,Bootstrap響應式底層原理和模擬實現。 ...
1.Bootstrap 的優缺點?
- 優點:CSS代碼結構合理,現成的代碼可以直接使用(響應式佈局)
- 缺點:定製流程較為繁瑣,體積大
2.如何實現響應式佈局?
- 原理:通過media query設置不同解析度的class
- 使用:為不同解析度選擇不同的class
3.如何定製自己的bootstrap樣式?
- 使用CSS同名類覆蓋(門檻低,見效快,可能會有bug)
- 修改源碼重新構建(一次性徹底解決)
[
bootstrap.scss是入口文件,修改這個文件內容之後,使用node-sass重新編譯scss文件
node-sass --output-style expanded bootstrap/custom/scss/bootstrap.scss > bootstrap/custom/dist/css/bootstrap.css
] - 引用Scss源文件,修改變數(類似於預處理器的使用方式, 徐亞什麼模塊引入什麼模塊,會更加靈活,推薦)
[
1. 創建一個自己的custom.scss文件
$primary: greed; @import './botstrap-custom/scss/bootstrap.scss'
]
4.如何實現一個響應式佈局框架?
[!NOTE]
面試常考考點,要求模擬實現boostrap的底層實現原理。
上面的[!NOTE]是行匹配模式,預設情況下支持類型NOTE,TIP,WARNING和DANGER。
4.1 JS的模擬實現
<style>
.container{
height: 40px;
margin: 0 auto;
background-color: rebeccapurple;
}
</style>
<div class="container"></div>
<script>
window.addEventListener("load", function () {
// 1. 獲取容器
let container = document.querySelector(".container");
let clientW = 0;
resize();
// 2. 監聽視窗的大小變化
window.addEventListener("resize", resize);
function resize() {
// 2.1 獲取改變後的寬度
clientW = window.innerWidth;
// 2.2 判斷
if(clientW >= 1200){ // 超大屏幕
container.style.width = "1170px";
}else if(clientW >= 992){ // 大屏幕
container.style.width = "970px";
}else if(clientW >= 768){ // 小屏幕
container.style.width = "750px";
}else { // 超小屏幕
container.style.width = "100%";
}
}
});
</script>
4.2 CSS的模擬實現
<style>
.container{
height: 40px;
margin: 0 auto;
background-color: rebeccapurple;
}
/*媒體查詢*/
@media screen and (max-width: 768px){
.container{
width: 100%;
}
}
@media screen and (min-width: 768px) and (max-width: 992px){
.container{
width: 750px;
}
}
@media screen and (min-width: 992px) and (max-width: 1200px){
.container{
width: 970px;
}
}
@media screen and (min-width: 1200px){
.container{
width: 1170px;
}
}
</style>
<div class="container"></div>
[!NOTE]
關鍵點:mediaQuery, 浮動,響應式佈局,resize事件