【Web】根據屏幕大小調整元素屬性(樣式)

使用css方式

html代碼

<h2>響應式判斷</h2>
<p class="example">操作瀏覽器窗口,查看效果。</p>

css樣式代碼

.example {
    padding: 20px;
    color: white;
}
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {
    .example {background: red;}
}

/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {
    .example {background: green;}
}

/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {
    .example {background: blue;}
} 

/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) {
    .example {background: orange;}
} 

/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {
    .example {background: pink;}
}

實現屏幕(窗口)不同大小,<p>標籤顯示不同的背景色;
css語法:(css有很多媒體類型)

@media mediatype and|not|only (media feature) {
    CSS-Code;
}

使用javascript方式

html代碼

<body class='sidebar-collapse'></body>

js代碼

<script>
	//dom加載完後執行:$(function() {}) 是$(document).ready(function()的簡寫
    $(function () {
        changeClass();
    });
 
    //瀏覽器的窗口大小發生改變時執行
    $(window).resize(function () {
        //執行代碼塊
        changeClass();
    });
 
    //當屏幕小於1400時添加一個屬性,大於的時候刪除屬性
    function changeClass() {
	    let ww = $(window).width();
	    if( ww > 1400 ){
	        $('body').removeClass('sidebar-collapse');
	    } else if( ww > 600 && ww < 1400 ){
	        $('body').addClass('sidebar-collapse');
	    }
    }
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章