我想使我的网站在以下情况下响应:
我在这里有点困惑,因为我在您的网站上观看的所有教程都是关于Bootstrap的,我不喜欢这样。
谢谢。
答案 0 :(得分:2)
我建议寻找免费的在线资源来学习媒体查询。我经常引用的两个质量值得信赖的来源是Mozilla Developer Network和W3 Schools。
以下是媒体查询的示例,如上面的第二个链接所示:
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
这个想法是先为较小的视口布局页面,然后随着屏幕尺寸变大,通常使用css更改布局。因此,术语“移动优先”。通常,这是进行布局的最佳方法,这不仅是因为移动Web流量已超过较大的查看端口Web浏览,而且还因为移动版本的网站趋向于更加简单和简化。随着视口大小的增加,增加复杂度变得容易了。
就汉堡包菜单而言,这里是W3 School's tutorial,可帮助您学习并提供一些可玩的代码。请确保将浏览器窗口缩小或放大以查看效果:
/* Toggle between adding and removing the "responsive" class to topnav when the user clicks on the icon */
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
/* Add a black background color to the top navigation */
.topnav {
background-color: #333;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
/* Change the color of links on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* Add an active class to highlight the current page */
.active {
background-color: #4CAF50;
color: white;
}
/* Hide the link that should open and close the topnav on small screens */
.topnav .icon {
display: none;
}
/* When the screen is less than 600 pixels wide, hide all links, except for the first one ("Home"). Show the link that contains should open and close the topnav (.icon) */
@media screen and (max-width: 600px) {
.topnav a:not(:first-child) {display: none;}
.topnav a.icon {
float: right;
display: block;
}
}
/* The "responsive" class is added to the topnav with JavaScript when the user clicks on the icon. This class makes the topnav look good on small screens (display the links vertically instead of horizontally) */
@media screen and (max-width: 600px) {
.topnav.responsive {position: relative;}
.topnav.responsive a.icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
}
<!-- Load an icon library to show a hamburger menu (bars) on small screens -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="topnav" id="myTopnav">
<a href="#home" class="active">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
发生的情况的基本概述是,结合样式(根据应用的媒体查询而变化)(在不同的视口宽度下),当点击汉堡包菜单时,样式也会发生变化,因为JavaScript .onclick method正在收听元素上的click事件。单击该元素后,JavaScript manipulates the DOM会通过更改其className property来更改该元素。通过应用不同的类,可以更改样式。简而言之,当有人单击汉堡包图标时,页面的布局就会更改。
因此,为了创建良好的移动响应性网站,而无需使用Bootstrap之类的框架,并且假设您对HTML有所了解,则至少应学习: