Bootstrap学习记录-part-01

本文详细介绍了Bootstrap 4中的布局容器、响应式断点、Z-index层级、网格系统及其应用,包括.col类的使用、适应性宽度设置、弹性盒子布局、内容对齐和排序等内容。

Bootstrap4的布局

Bootstrap的布局容器包括了两种:.container和.container-fluid。它们两者的区别在于前者是响应式布局,在遇到断点时会对于自身宽度进行适当的调整,而后者则全程保持100%的宽度,不过要注意的时尽管它们的宽度在大屏上都是100%,但是我们会发现它们两侧各有一部分空白,这是因为它们都保有两侧的13px的外边距。但是前者随着断点而进行宽度的自适应,所以到后来就不存在这个外边距了。那我们所提到的响应式断点到底是什么呢?

响应式断点的概念

所谓响应式的断点是针对屏幕分辨率的变化而衍生的概念。因为设备有各式各样的,大的屏幕有1200+px,如电脑的屏幕。而小的屏幕如手机的最小的却只有300+px的。而正由于这屏幕大小的差异,导致我们的网页如果不对他提前进行分辨率的适配,那么这个网页在不同设备间的显示就会出现异常。而这些断点就是针对不同大小宽度而规定的值,一般屏幕大小是这样划分的:

  • 屏幕宽度大小的划分

  • 超小屏幕:小于576px的
  • 小型屏幕:小于768px的
  • 中型屏幕:小于992px的
  • 大型屏幕:小于1200px的
  • 超大型屏幕:大于等于1200px的

关于Z-index

Z-index实际上时在CSS中就存在的一个属性,他是相对与x和y轴而言的,我们知道前面两个家伙分别代表了页面的横轴和纵轴,而这个Z也就是针对于页面与用户的轴了,因此他的数值越大,里用户距离就更近,所显示的层数也就更高,以下即为Bootstrap 4中的Z-index数值:

  • $zindex-dropdown 1000
  • $zindex-sticky 1020
  • $zindex-fixed 1030
  • $zindex-modal-backdrop 1040
  • $zindex-modal 1050
  • $zindex-popover 1060
  • $zindex-tooltip 1070

关于Bootstrap中的网格系统

我们在Bootstrap中通常将一个容器分为十二个列,而这种分栏需要两个类进行协作才能完成:.row和.col。这与表格中的行列就是一样的类,我们用一个行来包裹一个列。其中外面的行使用row即可,但是内部的行由于所需的宽度不同我们可以设置诸如col-4,col-3或者col-sm-4和col-md-6等等类来实现静态和适应性宽度的设置
之前我们提到了col-sm-4这种类,实际上-sm是一个适应性宽度的缩写,我们所有适应性的缩写前缀如下:

超小屏幕小型屏幕中型屏幕大型屏幕超大型屏幕
.col.col-sm-.col-md-.col-lg-.col-xl-
自动布局列

所谓自动布局列就是建立在网络系统基础之上的布局方式:

1.等宽列

我们之前有提到在一个容器之中我们共将其分为了12列,而这种细分则是由.row和.col两个类来实现的。其中具体的列即.col类有12种宽度形态,如果外加四个断点共计48种不同的宽度形态。而所谓的等宽列就是单纯的.col,这个.col可以是1也可以是1/12,这一切都取决于它是否与其他的.col并列,即假使一个.row中只有一个.col那么此时它便占据1的宽度,但是若有两个.col则每个只占1/2的宽度,以后的一次类推即可,那么这便是所谓的等宽列的概念。由此我们也能看出实际上这里我们所研究的.col列的概念实际上并非是是具体的宽度而是百分比的概念。

2.列宽的组合设计

之前我们提到了等宽列即单纯的.col,它并无修饰,这时如果我们希望生成一个布局:左翼占据2/3,右翼占据1/3则此时我们使用等宽列便无法实现,但是我们可以以.col-num的方式分别构造左右两个.col:.col-8和.col-4便可以实现理想效果了。而这种方式便使用了我们的列宽的组合使用

3.断点式的列宽组合设计

那么由上述所言,如果我们将断点融入其中便可以实现列宽的响应式布局了,如.col-xl-6和.col-sm-12两个值我们便可以发现在超大型屏幕上我们的布局是占据1/2而在小型屏幕则会占据1的宽度

4.等宽多列

我们之前所讨论的都是宽度,但是从类没有提及高度,那么我们知道在我们设计的列宽超出了12如.col-6和.col-7它们的组合便超出了12的宽度此时后者会被被迫换行,除此之外原先的空白处将会被保存为空白。如:
在这里插入图片描述

那么怎样才能实现跨列的同时还能跨行呢,这便要是有等宽多列来实现了。所谓等宽多列也就是利用.w-100这个类将原本的一行变为两行。其实如下:

<div class="row">
 <div class="col border py-3 bg-light">四分之一</div>
 <div class="col border py-3 bg-light">四分之一</div>
 <div></div>
 <div class="col border py-3 bg-light">四分之一</div>
 <div class="col border py-3 bg-light">四分之一</div>
</div>

此时页面将会变为:
在这里插入图片描述

删除边距

实际上在Bootstrap的默认网络和列间都是由边距的,因此有时会显得碍事。此时我们便可以使用.no-gutters类来实现边距的清除

排序

实际上在我们的布局中,我们的元素并非完全按照编写的顺序进行排列,我们可以使用.order-*这些类来对各个元素进行排序。其中*包含的值有1~12是个数字和first和last两个单词。数值越小就排列在最前面(左侧),而两个字母就见名知意了。但是要注意没有设置该属性的元素反而是默认最前置的,基本上是最优先的(除了first,它是至高优先的)

列的偏移

我们的列初始状态是遵循水平流的布局的,也就是一个接一个。但是我们有时需要实现诸如左右对称但是它们的宽度去不占据1/2.此时或许我们回想使用一个空的透明的列来实现,但是是实际上我们可以直接使用列的偏移也就是边距来实现。而列的边距(偏移的格式)写作:

.offset-(sm,md.lg.xl)-(0~11)

这里要注意的是我们这里的末尾数字是0开头的,即为只有11.除此之外我们要着重看一下这十二个值所代表的偏移百分比比值(向左偏移)

  1. 0%
  2. 8.34%
  3. 16.67%
  4. 25%
  5. 33.34%
  6. 41.67%
  7. 50%
  8. 58.34%
  9. 66.67%
  10. 75%
  11. 83.34%
  12. 91.67%
列嵌套

所谓列嵌套即是在一个类中我们再嵌套入一个行,然后在该行中我们可以在加入列,以此类推。从而实现一些特殊布局的需求。在这里我们额外提一下图文并行的方法。因为在很多情况下我们需要实现左侧或右侧图片而对侧是文字的效果。但是我们知道图片和文字放一起想实现这中效果并不容易,此时我们一是使用列的布局一种是使用.media作为主框架,嵌入图片而后再使用.meidia-body容器中加入文字的方式来实现这种效果,如:

 <div class="container">
        <div class="row">
            <div class="col-6">
                <div class="media">
                    <img src="Images/top-bac.png" alt="" srcset="">
                    <div class="media-body">
                        This is the photo!
                    </div>
                </div>
            </div>
        </div>
    </div>

Bootstrap的弹性盒子布局

相对于Bootstrap3的浮动布局,Bootstrap4采用的是弹性盒子。那么这个弹性盒子也就是我们display中的flex一值。而我们从它的名字:"弹性盒子"来看就知道这是一个可以按照屏幕宽度进行自适应的一个容器,故而也就更加易于布局。但是并非所有的容器都有flex属性,或者flex的属性并不合适,因为弹性盒子包括两种:flex和inline-flex。分别也就是弹性盒子和内联式弹性盒子。那么它们区别在哪呢?通过以下代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
.container{
    width: 400px;
    background-color: green;
    height: 40px;
    margin: 20px auto;
}
.box{
    background-color: yellowgreen;
    width: 200px;
    height: 40px;
}
.box-2{
    width: 500px;
    height: 40px;
    background-color: yellowgreen;
}
.d-flex1{
    display: flex;
}
.d-flex2{
    display: inline-flex;
}
span{
    color: #0780d8;
    font-size: larger;
    font-family: Georgia, 'Times New Roman', Times, serif;
}
</style>
<body>
   <h3> 子元素宽度小于父元素时使用flex</h3>
    <div class="container d-flex1">
        <div class="box"></div>
    </div>
    <span>Content Test</span>
    <h3>子元素宽度小于父元素时使用inline-flex</h3>
    <div class="container d-flex2">
        <div class="box"></div>
    </div>
    <span>Content Test</span>
    <h3>子元素宽度大于父元素时使用flex</h3>
    <div class="container d-flex1">
        <div class="box-2"></div>
    </div>
    <span>Content Test</span>
    <h3>子元素宽度大于父元素时使用inlineflex</h3>
    <div class="container d-flex2">
        <div class="box-2"></div>
    </div>
    <span>Content Test</span>
</body>
</html>

效果图如下:

在这里插入图片描述

由此我们发现了,使用flex属性值时。父容器保留了block的属性,因此它可以拥有外边距。。但是使用inline-flex后我们的父容器便失去外边距了,但是与常规的inline又有所不同的是,我们可以可以设置这个容器的宽度。而一般的行内式元素时无法设置宽度的。然后它们两者还有一个特点就是设置两个属性后其子元素都不会超过父容器的宽度,也就是不会被溢出。说了那么多我们来看一下Bootstrap中的对应类:.d-flex和.d-inline-flex。嗯是不是也设计得见名知意呢

排序方向

之前我们接触了排序的顺序,现在我们来看一下排序方向。那么在了解排序方向之前我们首先得明确在弹性盒子中子元素包括了水平和垂直得排列两个方式。

水平方向:

我们只需使用flex-row-reverse替代原有的flex-row即可,我们还可以为其添设响应式设置:

.flex-{sm|md|lg|xl}-row-reverse
垂直方向:

与前者是一样的我们只需要使用

.flex-column-reverse

即可实现自下至上得布局流

内容的排列

我们知道在CSS中,flexbox容器中我们可以设置其内容的位置,这内容不同于单纯的文本而包含了诸如子容器在内的。在flex-direction不为column(这种情况布局流是沿着y轴进行的)得情况下这种对齐方式都是相对于x轴而言的。
而在Bootstrap中其类名与原本CSS基本相似(注意这个类时放在容器内的与flexbox中容器使用该属性值一样),其包括以下几个类:

  • justify-content-start:目标位于容器的结尾(左翼)
  • justify-content-center:目标位于容器中心
  • justify-content-end:目标位于容器结尾(右翼)
  • justify-content-between:目标位于容器之间留有空白的容器之中
  • justify-content-around:目标位于容器之前,之后,之间都有空白的容器之中

自动对齐

前面我们提到了沿着x轴方向的父容器的类,现在我们需要看看设置在子元素本身上的y轴方向的对其方式,这与CSS中的基本属性也是类似的:

  • .align-self-start:仅靠顶部
  • .align-self-center:位于中央
  • .align-self-end:紧靠底部
  • .align-self-baseline:按照父元素的基准线,
  • .align-self-strech:将自身高度进行拉伸,内容位置不变,为默认的情况
  • 这个类也支持适应性布局

自动相等

该类.flex-fill的目的时是让子元素强制分配父元素的余下空间,有时子元素与父元素存在空白可使用该类来解决,注意他是使用在子元素之上的,该类也支持适应性布局格式

等宽变换

我们使用的类是.flex-grow-1,虽然乍一看是一样的效果,但是实际上从它的名字中我们知道该类当前的类仅仅设置了其flex-grow为1(对于flex-grow|shrink|basis以后会单独来说)

自动浮动

我们以上所提到的可以产生的浮动效果使用的是css的基本属性的直接使用,而实际上我们知道我们实现元素的居中或者左右上下移动经常离不开外边距。而所谓的自由浮动便是用的是该原理。其格式为:

.mr|mt|ml|mb-auto

弹性盒子中得wrap概念

所谓换行即为换行之意,而该概念对应的是CSS中的flex-wrap属性,这个属性主要的三个值,nowrap(默认),wrap和wrap-reverse等三个概念。所以说我们这个理使用的类也很简单,分别为:

.flex-{sm|md|lg|xl}-(no)wrap(-reverse)

内容的对齐

之前有提到justify-content和align-items。它们分别是针对flex容器的类,其次分别是对应x轴和y轴。而这里的align-content也是针对y轴的属性。它与前面的align-items很想,当有不完全一样。首先它比前者多一个属性值。且有部分值不一样,且同名属性除了strech都有所不同,首先共用元素部分:
center:前者的该属性设置后内容会至于容器中央,但是若出现两行时,这两行内容会在y轴方向留有空白。而该类则不会
start:都是紧靠左上进行排列的但是前者会在y轴方向留有空白
end:两者都收紧靠左下进行的排列,但是前者依旧会在y轴方向留有空白
stretch:它们的效果时一样的
不同部分:
baseline:前者的独有属性,与前者的start效果基本一致
between:后者专属,内容会在y轴上保持各较远的距离,如果是两行自一个紧靠上,另一个紧靠下,也就是保持空间平均分配
around:所有的多行元素保持上方和下方都有间距,空间平均分配

以下为相关的实验代码供参考

(鉴于无法上传文件,这里直接贴出网页源代码,至于Bootstrap请自行修改以导入,Bootstrap版本为4)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="bootstrap-4.6.1-dist/css/bootstrap.css">
</head>
<style>
.box{
    background-color: beige;
    width: 600px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0px auto;
}
.item{
    /* margin-left: 50px; */
    display: inline-block;
    width: 100px;
    height: 50px;
}

.item1{
    flex-grow: 1;
    background-color: blue;
}
.item2{
    flex-grow: 1;
    background-color: red;
}
.item3{
    flex-grow: 1;
    background-color: blueviolet;
}

.box-1{
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: aqua;
    width: 600px;
    height: 100px;
    margin: 20px auto;
}
.item-1{
    width: 300px;
    height: 50px;
}
.item4{
    flex-shrink: 1;
    background-color: blue;
}
.item5{
    flex-shrink: 2;
    background-color: red;
}
.item6{
    flex-shrink: 1;
    background-color: blueviolet;
}
.item-2{
    width: 100px;
    height: 50px;
    background-color: brown;
}
.item7{
    flex-grow: 1;
    background-color: blue;
}
.item8{
    flex-grow: 1;
    background-color: red;
}
.item9{
    flex-basis: 200px;
    background-color: blueviolet;
}
</style>
<body class="container">
  <h1>Average Fill</h1>
    <div class="d-flex bg-warning text-white">
      <div class="flex-fill p-2 bg-primary">Flex item1(Contains a lot )</div>
      <div class="flex-fill p-2 bg-success">Flex item2</div>
      <div class="flex-fill p-2 bg-danger">Flex item3</div>
  </div>
  <h1>Flex-Grow</h1>
  <div class="d-flex bg-warning text-white mb-4">
      <div class="p-2 flex-grow-1 bg-primary">Flex item1(Contains a lot)</div>
      <div class="p-2 flex-grow-1 bg-success">Flex item1</div>
      <div class="p-2 flex-grow-1 bg-danger">Flex item1</div>
  </div>
  <h1>Flex-grow</h1>
  <div class="box">
      <div class="item1 item"></div>
      <div class="item2 item"></div>
      <div class="item3 item"></div>
  </div>
  <h1>Flex-shrink</h1>
  <div class="box-1">
    <div class="item4 item-1"></div>
    <div class="item5 item-1"></div>
    <div class="item6 item-1"></div>
</div>
<div class="box-1">
    <div class="item7 item-2"></div>
    <div class="item8 item-2"></div>
    <div class="item9 item-2"></div>
</div>
<h1>Order in Row</h1>
<div class="row bg-light">
<div class="col-3 bg-primary">
    no-order
</div>
<div class="col-3 order-1 bg-danger">
    order-1
</div>
<div class="col-3 order-10 bg-success">
    order-10
</div>
<div class="col-3 order-5 bg-warning">
    order-5
</div>
</div>
<h1>Order in Div</h1>
<div class="d-flex bg-danger text-white">
    <div class="order-3 bg-primary m-2 p-2 flex-fill">
        Order-3    
        </div>
        <div class="order-2 bg-success m-2 p-2 flex-fill">
        Order-2
        </div>
        <div class="order-1 bg-warning m-2 p-2 flex-fill">
        Order-1
        </div>
        <div class="order-first bg-warning m-2 p-2 flex-fill">
            Order-first
        </div>
        <div class="bg-warning m-2 p-2 flex-fill">
            Order-none
        </div>
</div>
<h1>--Justify Content--</h1>
<h1>start</h1>
<div class="d-flex justify-content-start">
    <div class="col-3 badge-danger">Content Filler</div>
    <div class="col-3 badge-primary">Content Filler</div>
</div>
<h1>around</h1>
<div class="d-flex justify-content-around">
    <div class="col-3 badge-danger">Content Filler</div>
    <div class="col-3 badge-primary">Content Filler</div>
</div>
<h1>between</h1>
<div class="d-flex justify-content-between">
    <div class="col-3 badge-danger">Content Filler</div>
    <div class="col-3 badge-primary">Content Filler</div>
</div>
<h1>center</h1>
<div class="d-flex justify-content-center">
    <div class="col-3 badge-danger">Content Filler</div>
    <div class="col-3 badge-primary">Content Filler</div>
</div>
<h1>end</h1>
<div class="d-flex justify-content-end">
    <div class="col-3 badge-danger">Content Filler</div>
    <div class="col-3 badge-primary">Content Filler</div>
</div>
<h1>ALign-content-start</h1>
<div class="d-flex align-content-start bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
<h1>ALign-content-end</h1>
<div class="d-flex align-content-end bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
<h1>ALign-content-around</h1>
<div class="d-flex align-content-around bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
<h1>ALign-content-between</h1>
<div class="d-flex align-content-between bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
<h1>ALign-content-stretch</h1>
<div class="d-flex align-content-stretch bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
<h1>ALign-content-center</h1>
<div class="d-flex align-content-center bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
<h1>-------------Align-tiems</h1>
<h1>ALign-items-start</h1>
<div class="d-flex align-items-start bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
<h1>ALign-items-end</h1>
<div class="d-flex align-items-end bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
<h1>ALign-items-baseline</h1>
<div class="d-flex align-items-baseline bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
<h1>ALign-items-stretch</h1>
<div class="d-flex align-items-stretch bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
<h1>ALign-items-center</h1>
<div class="d-flex align-items-center bg-waring text-white flex-wrap mb-4" style="height: 150px;">
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
    <div class="p-2 bg-primary">This is the content here</div>
</div>
</body>
</html>
<think> 我们正在设计一个计算机专业学习视频网站。主要功能包括用户管理、视频管理、视频播放、分类浏览、评论等。 我们将使用Eclipse作为Java Web开发环境,MySQL作为数据库。 技术栈:Java Web(Servlet/JSP)、MySQL、HTML/CSS/JavaScript(前端) 步骤: 1. 数据库设计 2. 创建Eclipse动态Web项目 3. 配置数据库连接(使用JDBC) 4. 编写实体类(对应数据库表) 5. 编写DAO(数据库操作类) 6. 编写Servlet(处理请求) 7. 编写JSP(视图) 8. 前端页面设计 详细步骤及代码示例: 1. 数据库设计(MySQL) 创建数据库:`video_website` 创建表: - 用户表(user) - 视频表(video) - 视频分类表(category) - 评论表(comment) 具体表结构: 用户表(user): id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50) UNIQUE NOT NULL, password VARCHAR(50) NOT NULL, email VARCHAR(50), create_time DATETIME 视频分类表(category): id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL -- 分类名称,如:编程语言、数据结构、算法等 视频表(video): id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(100) NOT NULL, -- 视频标题 description TEXT, -- 视频描述 category_id INT, -- 所属分类 url VARCHAR(200) NOT NULL, -- 视频存储路径(或URL) user_id INT, -- 上传用户 create_time DATETIME, FOREIGN KEY (category_id) REFERENCES category(id), FOREIGN KEY (user_id) REFERENCES user(id) 评论表(comment): id INT PRIMARY KEY AUTO_INCREMENT, content TEXT, -- 评论内容 user_id INT, -- 评论用户 video_id INT, -- 所属视频 create_time DATETIME, FOREIGN KEY (user_id) REFERENCES user(id), FOREIGN KEY (video_id) REFERENCES video(id) 2. 在Eclipse中创建动态Web项目 - 打开Eclipse,选择File -> New -> Dynamic Web Project。 - 输入项目名称,例如:VideoWebsite。 - 配置Target runtime(如Tomcat)。 - 完成创建。 3. 配置数据库连接 将MySQL的JDBC驱动(mysql-connector-java-x.x.xx.jar)复制到项目的WebContent/WEB-INF/lib目录下。 创建数据库连接工具类(DBUtil.java),用于获取数据库连接。 ```java package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBUtil { private static final String URL = "jdbc:mysql://localhost:3306/video_website?useSSL=false&characterEncoding=utf8"; private static final String USER = "root"; private static final String PASSWORD = "123456"; static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(URL, USER, PASSWORD); } } ``` 4. 编写实体类(在src下创建包entity,然后创建以下类) 用户实体类(User.java): ```java package entity; import java.util.Date; public class User { private int id; private String username; private String password; private String email; private Date createTime; // 省略getter和setter } ``` 视频分类实体类(Category.java): ```java package entity; public class Category { private int id; private String name; // 省略getter和setter } ``` 视频实体类(Video.java): ```java package entity; import java.util.Date; public class Video { private int id; private String title; private String description; private int categoryId; private String url; private int userId; private Date createTime; // 省略getter和setter } ``` 评论实体类(Comment.java): ```java package entity; import java.util.Date; public class Comment { private int id; private String content; private int userId; private int videoId; private Date createTime; // 省略getter和setter } ``` 5. 编写DAO(数据访问对象) 以UserDAO为例(UserDAO.java): ```java package dao; import entity.User; import util.DBUtil; import java.sql.*; import java.util.ArrayList; import java.util.List; public class UserDAO { // 添加用户 public void addUser(User user) throws SQLException { String sql = "INSERT INTO user (username, password, email, create_time) VALUES (?, ?, ?, ?)"; try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, user.getUsername()); ps.setString(2, user.getPassword()); ps.setString(3, user.getEmail()); ps.setTimestamp(4, new Timestamp(user.getCreateTime().getTime())); ps.executeUpdate(); } } // 根据用户名查询用户(用于登录) public User getUserByUsername(String username) throws SQLException { String sql = "SELECT * FROM user WHERE username = ?"; try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) { ps.setString(1, username); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); user.setEmail(rs.getString("email")); user.setCreateTime(rs.getTimestamp("create_time")); return user; } } } return null; } } ``` 其他DAO类似(VideoDAO, CategoryDAO, CommentDAO)。 6. 编写Servlet(处理用户请求) 例如:处理用户注册(RegisterServlet.java) ```java package servlet; import dao.UserDAO; import entity.User; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; @WebServlet("/register") public class RegisterServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); User user = new User(); user.setUsername(username); user.setPassword(password); // 实际应用中需要对密码进行加密 user.setEmail(email); user.setCreateTime(new Date()); UserDAO userDAO = new UserDAO(); try { userDAO.addUser(user); // 注册成功,重定向到登录页面 response.sendRedirect("login.jsp"); } catch (Exception e) { e.printStackTrace(); // 注册失败,返回注册页面并提示错误 request.setAttribute("error", "注册失败,用户名可能已存在"); request.getRequestDispatcher("register.jsp").forward(request, response); } } } ``` 7. 编写JSP页面(视图) 注册页面(register.jsp): ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>注册</title> </head> <body> <form action="register" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> 邮箱:<input type="text" name="email"><br> <input type="submit" value="注册"> </form> <p style="color:red;">${error}</p> </body> </html> ``` 8. 前端页面设计 可以使用Bootstrap等前端框架来美化页面。 以上是一个基本的框架,实际开发中还需要考虑更多细节,例如: - 用户登录、退出 - 视频上传(需要文件上传处理) - 视频播放(可以使用HTML5的video标签) - 评论功能 - 权限控制(如未登录不能上传视频等) 由于篇幅限制,这里只给出了部分代码示例。具体实现时,需要根据功能需求逐步完善。 注意:实际项目中,密码存储应该使用加密(如MD5、BCrypt等),以上示例未做加密处理。 视频上传功能示例: 在VideoDAO中添加添加视频的方法: ```java public void addVideo(Video video) throws SQLException { String sql = "INSERT INTO video (title, description, category_id, url, user_id, create_time) VALUES (?, ?, ?, ?, ?, ?)"; // 类似UserDAO的addUser方法 } ``` 创建UploadVideoServlet处理视频上传(注意:视频文件的上传需要用到multipart/form-data,可以使用Apache Commons FileUpload库): ```java package servlet; // ...导入必要的包 @WebServlet("/uploadVideo") @MultipartConfig public class UploadVideoServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取表单数据 String title = request.getParameter("title"); String description = request.getParameter("description"); int categoryId = Integer.parseInt(request.getParameter("categoryId")); Part videoPart = request.getPart("videoFile"); // 视频文件 // 保存视频文件 String fileName = videoPart.getSubmittedFileName(); // 为防止文件名重复,可以重命名 String newFileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf(".")); // 存储路径(在web目录下创建一个videos目录) String savePath = getServletContext().getRealPath("/videos") + File.separator + newFileName; videoPart.write(savePath); // 获取当前登录用户(需要从session中获取,这里假设已经登录) User user = (User) request.getSession().getAttribute("user"); Video video = new Video(); video.setTitle(title); video.setDescription(description); video.setCategoryId(categoryId); video.setUrl("videos/" + newFileName); // 相对路径 video.setUserId(user.getId()); video.setCreateTime(new Date()); VideoDAO videoDAO = new VideoDAO(); try { videoDAO.addVideo(video); response.sendRedirect("index.jsp"); // 上传成功,跳转到首页 } catch (SQLException e) { e.printStackTrace(); // 失败处理 } } } ``` 视频播放页面(playVideo.jsp): ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>视频播放</title> </head> <body> <video width="640" height="480" controls> <source src="${video.url}" type="video/mp4"> 您的浏览器不支持视频播放。 </video> <h1>${video.title}</h1> <p>${video.description}</p> </body> </html> ``` 以上是一个简单的计算机专业学习视频网站的设计思路和部分代码示例。实际开发中还需要处理异常、日志、性能优化、安全性(如SQL注入、XSS攻击防护)等问题。 由于项目较为复杂,建议分模块逐步实现。 §§相关问题§§ 1. 如何优化视频网站的上传和播放功能? 2. 在Java Web项目中如何实现用户权限控制? 3. 如何设计一个推荐系统来推荐视频给用户? </think> 以下是使用Eclipse和MySQL设计计算机专业学习视频网站的详细思路和代码实现方案: ### 一、系统设计思路 1. **技术栈选择** - 后端:Java Servlet + JSP - 数据库:MySQL 8.0+ - 前端:HTML5/CSS3 + Bootstrap - 开发工具:Eclipse IDE + Tomcat服务器 2. **核心功能模块** ```mermaid graph TD A[用户模块] --> A1[注册/登录] A --> A2[个人中心] B[视频模块] --> B1[视频上传] B --> B2[分类管理] B --> B3[搜索功能] C[学习模块] --> C1[视频播放] C --> C2[进度跟踪] C --> C3[收藏功能] D[互动模块] --> D1[评论系统] D --> D2[问答社区] ``` 3. **数据库设计(MySQL)** ```sql -- 用户表 CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) UNIQUE NOT NULL, password VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, role ENUM(&#39;student&#39;, &#39;teacher&#39;, &#39;admin&#39;) DEFAULT &#39;student&#39;, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- 视频分类表 CREATE TABLE categories ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, -- 如:编程语言/算法/数据库等 parent_id INT DEFAULT NULL ); -- 视频表(核心) CREATE TABLE videos ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(200) NOT NULL, description TEXT, category_id INT NOT NULL, teacher_id INT NOT NULL, -- 上传教师ID video_url VARCHAR(255) NOT NULL, -- 视频存储路径 duration INT DEFAULT 0, -- 视频时长(秒) created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (category_id) REFERENCES categories(id), FOREIGN KEY (teacher_id) REFERENCES users(id) ); -- 学习记录表 CREATE TABLE learning_records ( user_id INT NOT NULL, video_id INT NOT NULL, progress FLOAT DEFAULT 0.0, -- 0.0~1.0 last_played TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (user_id, video_id), FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (video_id) REFERENCES videos(id) ); ``` ### 二、Eclipse项目结构 ``` /VideoLearningPlatform ├── src/ │ ├── controller/ # Servlet类 │ ├── dao/ # 数据库操作 │ ├── model/ # 实体类 │ ├── service/ # 业务逻辑 │ └── util/ # 工具类 ├── WebContent/ │ ├── WEB-INF/ │ │ ├── lib/ # JDBC驱动等JAR │ │ └── web.xml │ ├── videos/ # 视频存储目录 │ └── jsp/ # 视图文件 ``` ### 三、核心代码实现 1. **数据库连接工具类 (DBUtil.java)** ```java public class DBUtil { private static final String URL = "jdbc:mysql://localhost:3306/video_platform?useSSL=false&serverTimezone=UTC"; private static final String USER = "root"; private static final String PASSWORD = "your_password"; static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(URL, USER, PASSWORD); } } ``` 2. **视频实体类 (Video.java)** ```java public class Video { private int id; private String title; private String description; private int categoryId; private int teacherId; private String videoUrl; private int duration; private Timestamp createdAt; // Getter/Setter方法 public String getFormattedDuration() { int hours = duration / 3600; int minutes = (duration % 3600) / 60; int seconds = duration % 60; return String.format("%02d:%02d:%02d", hours, minutes, seconds); } } ``` 3. **视频上传Servlet (VideoUploadServlet.java)** ```java @WebServlet("/uploadVideo") @MultipartConfig public class VideoUploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取表单数据 String title = request.getParameter("title"); String description = request.getParameter("description"); int categoryId = Integer.parseInt(request.getParameter("category")); Part videoPart = request.getPart("videoFile"); // 视频文件存储 String fileName = UUID.randomUUID() + ".mp4"; String savePath = getServletContext().getRealPath("/videos") + File.separator + fileName; videoPart.write(savePath); // 获取当前用户(教师) HttpSession session = request.getSession(); User teacher = (User) session.getAttribute("user"); // 创建视频对象 Video video = new Video(); video.setTitle(title); video.setDescription(description); video.setCategoryId(categoryId); video.setTeacherId(teacher.getId()); video.setVideoUrl("videos/" + fileName); // 保存到数据库 VideoDAO videoDAO = new VideoDAO(); videoDAO.addVideo(video); response.sendRedirect("teacher/dashboard.jsp?msg=upload_success"); } } ``` 4. **视频播放页面 (play.jsp)** ```jsp <div class="container mt-4"> <div class="row"> <div class="col-md-8"> <video id="videoPlayer" controls class="w-100"> <source src="<%= request.getContextPath() %>/${video.videoUrl}" type="video/mp4"> 您的浏览器不支持视频播放 </video> <h3 class="mt-3">${video.title}</h3> <p>${video.description}</p> </div> <div class="col-md-4"> <div class="card"> <div class="card-header">课程目录</div> <ul class="list-group list-group-flush"> <c:forEach items="${relatedVideos}" var="v"> <li class="list-group-item"> <a href="play?id=${v.id}">${v.title}</a> <span class="badge bg-secondary float-end">${v.formattedDuration}</span> </li> </c:forEach> </ul> </div> </div> </div> </div> <script> // 记录播放进度 document.getElementById(&#39;videoPlayer&#39;).addEventListener(&#39;timeupdate&#39;, function() { let video = this; let progress = video.currentTime / video.duration; // 每隔10秒保存一次进度 if(Math.round(video.currentTime) % 10 === 0) { fetch(&#39;${pageContext.request.contextPath}/saveProgress&#39;, { method: &#39;POST&#39;, headers: {&#39;Content-Type&#39;: &#39;application/json&#39;}, body: JSON.stringify({ videoId: ${video.id}, progress: progress }) }); } }); </script> ``` ### 四、关键技术实现 1. **视频处理优化** - 使用FFmpeg进行视频转码(生成不同分辨率版本) - 前端使用HLS协议实现自适应码率 - 示例命令行转码: ```bash ffmpeg -i input.mp4 -c:v libx264 -crf 23 -preset medium \ -c:a aac -b:a 128k \ -vf scale=w=-2:h=720 -movflags faststart \ output_720p.mp4 ``` 2. **高效数据库查询(视频搜索)** ```java public List<Video> searchVideos(String keyword, int categoryId, int page) { String sql = "SELECT * FROM videos WHERE title LIKE ? "; List<Object> params = new ArrayList<>(); params.add("%" + keyword + "%"); if(categoryId > 0) { sql += " AND category_id = ? "; params.add(categoryId); } sql += " ORDER BY created_at DESC LIMIT ?, 10"; params.add((page-1)*10); try (Connection conn = DBUtil.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { for(int i=0; i<params.size(); i++) { stmt.setObject(i+1, params.get(i)); } try (ResultSet rs = stmt.executeQuery()) { // 结果集处理 } } } ``` 3. **安全注意事项** - 文件上传:限制文件类型、大小,重命名文件 - SQL注入:严格使用PreparedStatement - XSS防护:JSTL的<c:out>自动转义 - 敏感操作:添加CSRF Token保护 ### 五、部署流程 1. 在Eclipse中创建Dynamic Web Project 2. 导入MySQL JDBC驱动到WEB-INF/lib 3. 配置Tomcat服务器连接 4. 创建数据库并执行SQL脚本 5. 开发顺序建议: - 用户注册/登录 → 视频上传 → 视频列表 → 视频播放 → 学习记录跟踪 → 评论系统 ### 六、扩展功能建议 1. 视频推荐算法(基于用户学习记录) 2. 弹幕互动功能 3. 在线代码编辑器(集成Monaco) 4. 学习路径规划 5. 视频质量评估系统(用户评分)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值