lishihuan大约 158 分钟

前端

拖拽:https://blog.csdn.net/ee_11eeeeee/article/details/108566961open in new window

https://www.cnblogs.com/beyonds/p/13908289.htmlopen in new window

hu

色彩板:https://ant.design/docs/spec/colors-cnopen in new window

android studio 你的主机中的软件中止了一个已建立的连接 ----> 可能是 开热点导致端口被占

https://code.jquery.com/jquery-1.11.3.jsopen in new window

盒子模型;https://blog.csdn.net/miss_zxm/article/details/80271161open in new window

https://www.cnblogs.com/Wayou/p/jquery_plugin_tutorial.htmlopen in new window

待整理:https://www.cnblogs.com/theblogs/p/10516098.htmlopen in new window

https://www.cnblogs.com/ichenchao/articles/12659852.htmlopen in new window

https://xuqichuang.gitbook.io/es6/open in new window es6

https://www.haorooms.com/post/javascript_neicun_useopen in new window

js 面向对象编程实例

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Referenceopen in new window

测试用图

'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'

命名

  • wrap/wrapper : 容器
  • container
  • popup:弹出
  • Popover:弹窗窗口
  • content:内容
  • title: 标题
  • backdrop 背景;背景幕
  • head
  • Toast / hint / tips 提示
  • footer
  • body
  • custom 自定义
  • delete、del 删除
  • item-card item-card__inner-card
  • extData

目前三大主流前端框架

1. vue.js

异常及处理

解决:'vue-cli-service' 不是内部或外部命令,也不是可运行的程序 或批处理文件:https://www.jianshu.com/p/4bb4ce82fb20open in new window

npm install -g @vue/cli-service

2. React

  • 起源于Facebook的内部项目,2013年 开源,同Vue一样是UI层的框架;
  • 首次提出虚拟DOM和JSX语法,推崇组 件式开发;
  • 能给人带来不一样的coding感受,生态 丰富;
  • 学习成本跟Vue比的话较高

3. Angular

  • 由谷歌推出,之前一段时间在疯狂地迭 代更新,是一款真正意义上的框架;

  • 同样提倡组件化、双向数据绑定、语义化标签等理念;

  • 模板功能强大,自带丰富的Angular指令,可扩展HTML;

  • 引入了Java的一些东西,有依赖注入等功能点,很容易编写可复用的代码;

  • 学习成本较高。



19.html

HTML转义字符大全

https://blog.csdn.net/chb_1_2/article/details/80728732open in new window

css 选择器:https://blog.csdn.net/u013275171/article/details/84504475open in new window

height: calc(100% - 73px);
$(".wdzb_detail_warp").css('height','calc(100% - 20.11rem)');

flex: 1;/*用来均分空间的*/

开发常用的几个css

/**
 放置一些  公共样式
 */
/*公共样式*/
.popup_window {
    padding: 0;
    margin: 0;
    width: 100%;
}

/*弹窗样式*/
.popup_window{
    color: #FFFFFF;
    height:100%;
}
/* 弹窗主色调 */
.popup_window_background{
    color: #FFFFFF;
    /*background: rgba(60, 61, 115, 0.3);*//* rgba(0,56,114,0.8); */
    box-shadow: 0px 0px 15px 0px rgba(24, 249, 234, 0.25);
}
/*隐藏*/
.none {
    display: none;
}
.pr{
    position: relative;
    /*display: flex*/
}
.pa{
    position: absolute;
}
/*辅助开发*/
.bk{
    border: 1px solid #ccc;
    box-sizing: border-box;
}
/*重要属性,设置元素padding 等属性 也可以保证 元素不超出父容器*/
.bs{
    box-sizing: border-box;
}
/*居中*/
.ty_50{
    top: 50%;
    position: absolute;
    transform:translateY(-50%)
}
/*居中 不能 对行内元素使用,例如 display: inline-block;*/
.div_text_jz{
    display: flex;
    align-items: center;
}
/*对行内元素 垂直居中*/
.div_text_jz2{
    display: inline-flex;
    align-items: center;
}
/*搭配  div_text_jz  用于水平居中*/
.jc_c{
    justify-content: center;
}
/*均匀排列每个元素,每个元素之间的间隔相等*/
.df_s{
    display: flex;
    align-items: center;
    justify-content: space-evenly;
}

/*  横向排列 垂直居中,中间 均匀排列*/
.df_sb{
    justify-content: space-between;
    display: flex;
    align-items: center;
}
/* 竖向排列并居中*/
.vertical_pl{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
}
/*盒子模型中两端对其*/
.jc_sb{
    justify-content:space-between;
}
/* 右对齐*/
.align_right{
    display: flex;
    align-items: center;
    justify-content: flex-end;
}
/* 自动换行 并且垂直居中*/
.flex_auto{
    display: flex;
    flex-flow: row wrap;
    align-items: center;
}
/*文字只排列2行*/
.outer {
    overflow: hidden;
    text-overflow: ellipsis;
    /*设置成弹性盒子 */
    display: -webkit-box;
    /*显示的个数 */
    -webkit-line-clamp: 2;
    /* 属性规定框的子元素应该被水平或垂直排列。 */
    -webkit-box-orient: vertical;
}
/* 水平居中*/
.ta-c{
    text-align: center;
}
/*光标*/
.cursor_pointer{
    cursor:pointer;/*光标样式-小手*/
}
.cursor_default{
    cursor:default;/*光标样式 指针*/
}
/*超长*/
.long_omit{overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}
/*超长省略,针对 long_omit 无法使用的场景*/
.long_omit2{display:block;text-overflow: ellipsis;white-space: nowrap;}
/*文字最多2行,超出省略*/
.long_omit3{
    white-space: unset;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    overflow: hidden;
    -webkit-box-orient: vertical;
}
/*块元素转  行内块元素*/
.dib{
    display:inline-block;
    vertical-align:top
}
.di{
    display:inline;
}
.fl{
    float: left;
}
/*弹窗内容部分*/
/*内容部分中,标题  */
.content_title{
    color: #FFFFFF;
}
.content_color{
    color:#4FF0FD;
}
/*搭配  display: inline-block*/
.f0{
    font-size: 0;/*子元素 用 display: inline-block; 会导致 元素之间 存在空隙 所以设置  font-size: 0*/
}
/*高亮颜色*/
.highlight_font{
    color: #4deaf8;
}

.h25{
    line-height: 25px;
    height: 25px;
}
.h30{
    line-height: 30px;
    height: 30px;
}

.f18{ font-size: 18px; }.f20{font-size: 20px;}.f22{ font-size: 22px; }.f25{font-size: 25px;}.f30{font-size: 30px;}.f35{font-size: 35px;}

.pl20{
    padding-left: 20px;
    box-sizing: border-box;
}
.p20{
    padding: 20px;
}
.wh100{
    width: 100%;
    height: 100%;
}
.left_top_005{
    background: url(../map/3DmapImages/tower/tower_left_f_005.png) no-repeat center;
    background-size: 100%100%;
    width:762px;
    height:150px;
}
.left_top_005_ls{
    background: url(../map/3DmapImages/tower/tower_left_f_005_ls.png) no-repeat center;
    background-size: 100%100%;
    width:762px;
    height:150px;
}

.main_background {
    background-color: rgb(52, 106, 181, 0.8);
    color: #FFFFFF !important;
    box-shadow: 0px 0px 15px 0px rgba(24, 249, 234, 0.25);
}
.div_button{
    box-shadow: 0 0 10px #4a90d8 inset, 0px 0px 30px rgb(0,153,184);
    font-family: Microsoft YaHei;
    font-size: 1.2em;
    font-weight: 600;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    cursor: pointer;
    height: 100%;
    color: #f5f5f5;
    border: 1px solid #2f4aa1;
    background: #0e3056;
}
.zdy_button:hover  {
    transform: scale(1.1);
    transition: all 0.6s;
}
.zdy_button:active {
    opacity: 0.1;
    transform: scale(1.1);
}
.div_button:hover  {
    transform: scale(1.1);
    transition: all 0.6s;
}

/*文字两端 对其,,在父容器上*/
.justify {
    justify-content: space-between;
    display: inline-flex;
    align-items: center;
}
.hidden{
    display: none;
}


/*自定义滚动条*/
.resultHtml{
    overflow: auto;
        /*scrollbar-width: none;*//* 火狐浏览器 自定义 滚动条没生效*/
    /* 针对火狐浏览器*/
    scrollbar-width: thin;
    scrollbar-color: #535353 #EDEDED;
}
.resultHtml::-webkit-scrollbar { /*滚动条整体样式*/
    width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 4px;
}

.resultHtml::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #535353;
}

.resultHtml::-webkit-scrollbar-track { /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 10px;
    background: #EDEDED;
}
/* 自定义弹出层*/
.popup_wrap{
    height: 200px;
    width: 150px;
    box-shadow: 0 0 10px #4a90d8 inset, 0px 0px 30px rgb(0,153,184);
    font-family: Microsoft YaHei;
    font-size: 1.2em;
    font-weight: 600;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    cursor: pointer;
    background: rgb(0,0,0,0.8);
    color: #f4f4f4;
    border-radius: 5px;
    opacity: 0;
    left: 0px;
    top: 0px;
    padding: 10px;
    z-index: 999;
}
.popup_wrap .item{
    padding: 5px 0;
    transition: all 0.6s;
    display: flex;
    align-items: center;
    justify-content: center;
}
.popup_wrap .item:hover{
    color: #13c3e3;
    background: #0e3056;
    /*transform: scale(1.1);*/
}
.popup_wrap .item.check{
    color: #13c3e3;
    background: #0e3056;
    /*transform: scale(1.1);*/
}
.popup_icon{
    padding-right: 10px;
}
/* HTML中解决双击会选中文本的问题*/
.html_wrap{
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}


/* 标签*/
.right_label_wrap{
    position: absolute;
    padding: 3px 6px;
    border: 1px solid #cca4e3;
    border-radius: 5px;
    background-color: rgb(87, 189, 77,0.4);
    /*box-shadow: 0 0 10px #4a90d8 inset, 0px 0px 30px rgb(0,153,184);*/
    box-shadow: 0px 5px 5px #888888;
    display: flex;
    align-items: center;
    box-sizing: border-box;
    color: #f5f5f5;
}
/* 动画 可以 作为 图片按钮 */
.img_button:hover{
    transform: scale(1.1);
    transition: all 0.6s;
}
.img_button:active{
    animation-name: example;
    animation-duration: 4s;
}
@keyframes example {
    0%   {opacity: 0;}
    25%  {opacity: 1;}
    50%  {opacity: 0.4;}
    100% {opacity: 1;}
}
/* 响应式 Web 设计 - 网格视图*/
* {
    box-sizing: border-box;
}
.row:after {
    content: "";
    clear: both;
    display: block;
}
[class*="col-"] {
    float: left;
}
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
/* 自定义 table 搭配 上面的 网格视图*/
.table_row {
    margin: 10px 0 0 0;
    background: rgba(3, 135, 188, 0.2);
    display: flex;
    align-items: center;
}
.table_col {
    height: 50px;
    line-height: 50px;
    font-size: 20px;
    font-family: Source Han Sans CN;
    font-weight: bold;
    color: #B8EAFF;
    text-align: center;
    padding: 0 10px;
    cursor: default;
    overflow: hidden;
    text-overflow: ellipsis;
    display: block;
}
.table_row:hover{
    /*transform: scale(1.1);*/
    background: rgba(3, 135, 188, 0.6);
}
.table_title {
    height: 73px;
    font-size: 25px;
    font-family: Source Han Sans CN;
    font-weight: bold;
    color: #B8EAFF;
    /* margin-bottom: 10px; */
}

/* 自定义 input 设置为 透明 ,去掉边框 */
.zdy_input{
    width: 90px;
    height: 100%;
    font-size: 1.2vh;
    font-weight: 400;
    color: #f5f5f5 !important;
    margin: 0px !important;
    /*border: 1px solid #2f4aa1 !important;*/
    border: none !important;
    box-sizing: border-box;
    background: none !important;
}


.plf5{padding-left:5px;padding-right:5px;}
.plf10{padding-left:10px;padding-right:10px;}
.plf15{padding-left:15px;padding-right:15px;}
.plf20{padding-left:20px;padding-right:20px;}
.br10{border-radius: 10px;}

案例:居中

image-20201028193829196
image-20201028193829196
/*使用 display: flex;   
	说明:display: flex实现块转行内元素 (不用使用display:inline-block 属性实现,因为需要父节点字体大小为0))
		然后使用  align-items: center; justify-content: center 实现垂直,水平居中
*/
<div class="box_background_style"><!--box_background_style 背景图片 -->
    <div class="div_text_jz bs cursor_pointer">
        <div class="div_text_jz jc_c" style="width: 80%;height: 100%;">天气情况</div>
        <div class="div_text_jz jc_c" style="width: 20%;height: 100%;">
            <img src="${ctxStatic}/dvp3D/imgs/ionic_002.png" >
        </div>
    </div>
</div>
<style>
.box_background_style{
    background: url(${ctxStatic}/dvp3D/imgs/ionic_001.png) no-repeat center;
    background-size: 100% 100%;
    width: 258px;
    height: 84px;
}
</style>

案例: 获取鼠标图片放大

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			div{/*默认图片样式*/
				width: 300px;
				height: 300px;
				border: #000 solid 1px;
				margin: 50px auto;
				overflow: hidden;
			}
			div img{/* 动画 延迟*/
				cursor: pointer;/**/
				transition: all 0.6s;/*动画*/
			}
			div img:hover{/* 获取光标 放大1.4倍*/
				transform: scale(1.4);
			}
		</style>
	</head>
	<body>
		<div>
			<img src="img/focus.png" />
		</div>
	</body>
</html>

19.1中元素居中

  • 利用相对定位
parentElement{
	position:relative;
}
childElement{
	position: absolute;
	top: 50%;
	transform: translateY(-50%);
}
baseline默认。元素放置在父元素的基线上。
sub垂直对齐文本的下标。
super垂直对齐文本的上标
top把元素的顶端与行中最高元素的顶端对齐
text-top把元素的顶端与父元素字体的顶端对齐
middle把此元素放置在父元素的中部。
bottom把元素的顶端与行中最低的元素的顶端对齐。
text-bottom把元素的底端与父元素字体的底端对齐。
length
%使用 "line-height" 属性的百分比值来排列此元素。允许使用负值。
inherit规定应该从父元素继承 vertical-align 属性的值。

可以控制图片、文字等行内元素在行内的垂直方向上的对齐方式

如何使用vetical-align使块级元素垂直居中?

以下面为例:

<body>
	<div class="wrapper">    
		<div class="content">some content</div>  
	</div>
</body>

1、为父容器wrapper设置高度

html,body{
	height:100%
}
.wrapper{
	height:100%
}

2、使content容器变为行内元素

.content{  display:inline-block;}

3、利用before伪元素在content容器之前构造一个空内容的inline-block

.wrapper:before{  content:"";  display:inline-block;  height:100%;  vertical-align:middle;}

此时,整个页面只有一行,其中有两个inline-block,让空内容行内上下对齐

4、为content容器添加vetical-align属性

.content{
	vertical-align: middle;
}

这样,块级元素在浏览器中始终都是垂直对齐的

19.2几种居中的方法总结

  • 元素 竖排,并且居中
 display: flex;
 align-items: center;
 justify-content: center;/*子元素水平居中*/
  • 1.vertical-align: middle

  • 2.position: absolute;top: 50%;transform: translateY(-50%),

  • 3.height,line-height

  • 4.不设置高度,通过padding 将内容撑起来

  • 5.父:display: flex;子:align-self: center; (垂直居中) align-items: center;(水平居中)

    在父节点上添加 注:display: inline-flex; inline-flex对 行类块元素使用,替代 display: inline-block块转行;display: flex;对块元素使用

    display: flex;定义下的子元素 默认水平排列

  • 子项使用 margin:auto

需要注意,text-align: center; 文本水平居中,在快元素是不支持的,对于快元素需要将 子项div 转为行内元素(或行内块元素)

<!-- 场景1 使用 text-align: center; 那么需要将 子项div 转为行内元素(或行内块元素) --> 
<style>
    .f_div{
        text-align: center;
        border: 1px solid #ccc;
        width: 100%;
        height: 320px;
        top: 40px;
    }
    .z_div{
        width: 300px;
        background: red;
        height: 100%;
        /* margin: auto; */
        border: 1px solid #ccc;
        display: inline-block;
    }
    
</style>

<div class="f_div" id="map_xunjian_count" style=" ">
    <div class="z_div">div水平居中</div>
</div>
<!-- 场景2 子项div 不转为 行内元素,则 需要使用 --> 
<style>
    .f_div{
        /*text-align: center; 取除,对 块元素不起作用 */
        border: 1px solid #ccc;
        width: 100%;
        height: 320px;
        top: 40px;
    }
    .z_div{
        width: 300px;
        background: red;
        height: 100%;
        margin: auto;
        border: 1px solid #ccc;
        /*display: inline-block;*/
    }
    
</style>

<div class="f_div" id="map_xunjian_count" style=" ">
    <div class="z_div">div水平居中</div>
</div>

案例 img标签在div中水平垂直居中

  • 第一种方式: text-align:center; vertical-align:middle;
<style>
    div{
        text-align: center;
        vertical-align:middle;width: 400px;
        height: 400px;
        border: 1px solid #000;
    }
    img{vertical-align: middle}
    span{height: 100%;vertical-align: middle;display: inline-block}
</style>
<div style="">
    <span></span>
    <img src="ad-pic.png" alt="" style="border: 1px solid #000;">
</div>
  • 第二种
<div  style="position: relative;padding: 8px 8px 8px 50px;">
		<img src="img/kaoqin.png" alt="" style="height: 20px;position: absolute;top: 50%;transform: translateY(-50%);left: 16px;">
		<span style="">到位情况:</span><span>未到位到位沃尔沃欸范围划分骗我呢覅普无不佩服违法未u符合我二号</span>
</div>
img
img

注: 第二种方法,待定,父节点下的img 不应该设置 top: 50%;transform: translateY(-50%); 而是 内容高度和图片高度设置一致,然后由padding 将内容撑起,其中父节点也不设置 height,line-height

最优

img
img
<div style="position: relative;padding: 16px 0 16px 50px;font-size: 25px;">
<img src="/TPCloud/static/map/3DmapImages/ionic001.png"  style="width:40px;left: 0px;position: absolute;">
	<div class="dib">GT信息</div>
</div>
  • 第三种 使用 height,line-height
<div  style="border: 1px solid #ccc;text-align: center;width: 50px;height: 50px;line-height: 48px;border-radius: 50%;">内容</div>

第四种方式 :不设置高度,通过padding 将内容撑起来

img
img
.item {
  margin: -1px;/*上图中出现的左右测的边线 可以通过,margin:-1px隐藏再容器中*/
  padding: 16px;
  border: 1px solid #ddd;
}
/* 超长字符的处理,white-space: nowrap; 是用省略号代替,white-space: inherit; 不显示,自动可以强制换行*/
.item-content p {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
  • 第五种: 父节点设置display:flex; 子节点设置 align-self: center 属性(目前最优)

19.3 使用 position:absolute 下的水平居中

场景在地图开发中添加的标题 需要 使用相对定位 脱离文档流

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <style>
  .con{
      width:200px;
      height:200px;
      background:#ccc;
      position:relative;
    }
  </style>
</head>
<body>
<div class="con">
  <div class="abs"></div>
</div>
</body>
</html>

css 实现: 2种 方式 ,第一种使用 margin:0 auto; 第二种使用 transform:translate(-50%);

/*
	场景1:核心在于  left:0; right:0; margin:0 auto;
*/
.abs{
  width:40px;
  height:20px;
  background:steelblue;
  position:absolute;
  bottom:0;
  left:0;/**/
  right:0;
  margin:0 auto;
}
/*
	场景2:核心在于 left:50%; transform:translate(-50%);
*/
.abs{
  width:40px;
  height:20px;
  background:steelblue;
  position:absolute;
  bottom:0;
  left:50%;
  transform:translate(-50%);
}

案例 :图片+多行文字 布局

image-20201123192717342
image-20201123192717342
<style>
	.menu_div{
        width: 300px;
        color: #ffffff;
        -webkit-border-radius: 15px !important;
        padding: 0px 14px 0px 120px;
	}
	.meun_div_img{
	  width: 32%;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      left: 8px;
	}
	.meun_div_a{
	 	color: #18eaf9;
          vertical-align: bottom;
          font-size: 40px !important;
          font-family: 'electronicFont';
	}
</style>
<div class="bs pr main_background menu_div">
  <img src="/CPMS/static/map/arcgis4.x/images/left_meun/ionic_left_menu_002.png" class="meun_div_img"/>
  <div class="overlength" style="font-size: 25px; padding: 10% 0px; width: 100%" >
    <div style="padding-bottom: 10px">今日在建工程数</div>
    <div style="text-align: center">
      <a class="meun_div_a" >0</a>
      <span style="font-size: 20px">(项)</span>
    </div>
  </div>
</div>

19.6 案例 (需要完善,很多class属性没记录下来)

<div class="searchBox" style="padding:30px 20px;">
	<p class="inBox top00" style="width: 70%;display: inline-block;">
		<i class="icon ion-ios-search placeholder-icon"></i>
		<input style="background: #EEEEEE;color:#000000;height: 40px;border-radius: 22px;" ng-change="changeSearch()" ng-model="inputSearch"                 type="text" placeholder="请输入关键字..." />
	</p>
	<button class="button button-clear button-primary" style="color: #0CABA4;position: absolute;top: 50%;transform: translateY(-50%);right: 		10px;" ng-click="modal.remove()">取消</button>
</div>	
img
img

19.7 HTML行内元素、块状元素、行内块状元素的区别open in new window (行转块)

HTML可以将元素分类方式分为行内元素、块状元素和行内块状元素三种。这三者是可以互相转换的,使用display属性能够将三者任意转换:

  • display:inline;转换为行内元素

    特点:

    • m没有宽和高;
    • 元素和其他元素共占一行;
  • display:block;转换为块状元素

    块级元素的特点是:可以给元素设置宽高,元素独占一行;

  • display:inline-block;转换为行内块状元素

使用display:inline-block 会出现2个问题

  1. 错位

解决

.dib{
  	display:inline-block;
    vertical-align:top;
  }

2.换行,2个div中间出现空隙,导致换行(display:inline-block表示行内块元素,后面自带空格字符)

解决:在父系上加font-size:0 注:一定是在 父 节点上加 font-size:0px

对于 table:每个tr存在间隙 用 border-spacing:0;

添加padding,添加边框等 导致 超出父容器 处理

/*元素添加padding,为了防止超出父容器,添加box-sizing: border-box; 属性*/
.p20{
	padding: 20px;
	box-sizing: border-box;
}

19.8 html 常用的一些属性

  • div 内的文本不能换行 可能 white-space: normal;

  • 固定底部 (定位最下面)position: fixed

  • 透明度

    • opacity设置颜色然后透明度(但是会导致文字也模糊了) background-color: #658fce; opacity: 0.8;
  • background: rgba(0, 0, 0, 0.5)

.main_background{
        background-color:rgb(52, 106, 181,0.6);
        color: #FFFFFF !important;
        box-shadow: 0px 0px 15px 0px rgba(24, 249, 234, 0.25);
}
  • align 控制元素位置
    • left 左对齐内容。
    • right 右对齐内容。
    • center 居中对齐内容。
    • justify 对行进行伸展,这样每行都可以有相等的长度(就像在报纸和杂志中)。
  • text-align:center; 水平居中
  • vertical-align:middle; 垂直居中 ( vertical-align: bottom; 可使div 中的文字 底部靠齐)
  • 文字的间距 .divcss5
  • 行间距(行高)line-height:30px
  • 去掉边框 style="border: medium none;" 或者style="border:none;"
  • 元素的显示和隐藏
<div  id="ceshi" style="display:none;"></div>		---元素被隐藏
在js方法中 $("#ceshi").show();					---影藏的元素显示出来
 			$("#tianjiaHtml").show();
			$("#hiddenHtml").css("display","none")
$("#btnSubmit").removeAttr("disabled"); --------取消某个属性  对于disabled  属性  一但使用 对应的控件是无法通过  设置属性attr("disabled","flase");来取消的
display:none或visibility:hidden
visibility:hidden可以隐藏某个元素,但隐藏的元素仍需占用与未隐藏之前一样的空间。也就是说,该元素虽然被隐藏了,但仍然会影响布局

显示:style="display:block"或者 $('#div_1').show();
隐藏:style="display:none"或者$('#div_2').hide();
  • title 信息提示
<tr title="${task.rwdName}&#13;${task.office.name}&#13;${task.substation.name}">  <!--注:  &#13;是用来换行-->
  • 删除按钮,那么可以("#....").empty() 或者是.html(" ")--------删除的是标签的内容 ,,如果要删除标签用("#...").remove(); $(this).next("label").remove();

  • transform 旋转、缩放、倾斜、移动,变形 CSS3中的变形处理

https://blog.csdn.net/qq_40542728/article/details/81979163open in new window

https://developer.mozilla.org/zh-CN/docs/Web/CSS/transformopen in new window

transform的scale缩放属性,搭配 transform-origin属性 可进行页面适配,同样的还有zoom属性

暂时没做总结

于这个属性搭配的 transform-origin

  • 注: 页面中 元素位置移动可以通过 append 将指定的元素 迁移到 指定的位置

    ​ 例:A元素下有一个 div 想将 这个div迁移到 B元素下,直接(B).append((B).append((A).children())

transform: translate3d(0px, 0px, 0px) scale(1);/* 定义元素位置和 大小*/
  • 设置渐变色
background: radial-gradient(rgb(5 243 251) 12%,rgb(21 67 77)80%);
background: -webkit-gradient(linear,0 0,0 bottom, from(rgba(255,140,17,0.7)),to(#ff8c11));

background: linear-gradient(8deg,rgb(15,229,236,0.1) 20%,rgb(11 232 232 / 80%) 82%,rgb(15,229,236,0.2) );//
/* 一条竖线*/
border-right: 10px solid;
border-image: linear-gradient(rgb(21 67 77),rgb(5 243 251),rgb(21 67 77))1 10 1;
  • 圆角 radius
border-top-right-radius: 5px;
border-top-left-radius: 5px;

border-radius: 5px;
  • 指针(光标)
<html>
<body>
  <p>请把鼠标移动到单词上,可以看到鼠标指针发生变化:</p>
  <span style="cursor:auto">光标</span><br />
  <span style="cursor:crosshair">十字</span><br />
  <span style="cursor:default">指针</span><br />
  <span style="cursor:pointer">小手</span><br />
  <span style="cursor:move">移动</span><br />
  <span style="cursor:e-resize">左右拉</span><br />
  <span style="cursor:ne-resize">对角拉</span><br />
  <span style="cursor:nw-resize">对角拉</span><br />
  <span style="cursor:n-resize">上下拉</span><br />
  <span style="cursor:se-resize">对角拉</span><br />
  <span style="cursor:sw-resize">对角拉</span><br />
  <span style="cursor:s-resize">上下拉</span><br />
  <span style="cursor:w-resize">左右拉</span><br />
  <span style="cursor:text">光标</span><br />
  <span style="cursor:wait">等待</span><br />
  <span style="cursor:help">问好</span>
</body>
</html>
box-shadow: 0px 0px 15px 0px rgba(24, 249, 234, 0.4);
box-shadow: 0 0 10px #178236 inset, 0px 0px 30px rgb(0,153,184);

说明:

1.box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);

例:<div style="box-shadow: 0 0 10px #f00; border:1px solid green"></div>box-shadow: 0 0 10px #f00 (因没有使其X轴与Y轴移动 设置值 所在会在本身发生作用 半径范围,颜色)

box-shadow: 0 0 10px #f00;

1.box-shadow内外阴影,单边阴影 ###box-shadow基本用法 语法说明:

box-shadow: h-shadow v-shadow blur spread color inset;

h-shadow 必需。水平阴影的位置。允许负值。

v-shadow 必需。垂直阴影的位置。允许负值。

blur 可选。模糊距离。

spread 可选。阴影的尺寸。

color 可选。阴影的颜色。请参阅 CSS 颜色值。

inset 可选。将外部阴影 (outset) 改为内部阴影。

x轴,y轴,阴影模糊距离,阴影颜色。

其中x-offset为正值时,生成右边阴影,反之为负值,生成左边阴影;y-offset为正值时,生成底部阴影,反之生成顶部阴影;阴影模糊半径如果为0,则 生成实影效果。如果加上阴影模糊半径,阴影清晰度向外扩散,更具阴影效果

2.内阴影,只需要加上属性inset

.shadow{
  box-shadow: inset 2px 2px 2px red;//box-shadow:inset 0px 0px 14px 0px rgba(24, 249, 234, 0.35);
}

3.单边阴影

单边上边阴影 box-shadow:inset 0 4px 5px -3px blue;

单边左边阴影 box-shadow:inset 4px 0 5px -3px green;

单边下边阴影box-shadow:inset 0 -4px 5px -3px red;

单边右边阴影 box-shadow:inset -4px 0 5px -3px orange;

  • css选中器
  <div class="f1 f1_1"></div>
  <!-- 
  	.f1.f1_1{} 表示 当前元素 有class='f1 f1_1'  <div class="f1 f1_1"></div>
  	.f1 .f1_1{} 中间有个空格,表示 class="f1" 下一个子元素 有个class="f1_1"  <div class="f1"> <div class="f1_1"></div></div>
  -->
  • calc
height: calc(100% - 165px);
  • 标题使用时用 font-weight: 900; 设置还是不够粗 ,可以设置字体
font-family: Arial, Helvetica, sans-serif;/* 字体会显得粗*/ 

蘋果儷細宋:Apple LiSung Light

Windows的一些:

新細明體:PMingLiU

細明體:MingLiU

標楷體:DFKai-SB

黑体:SimHei

新宋体:NSimSun

仿宋:FangSong

楷体:KaiTi

仿宋_GB2312:FangSong_GB2312

楷体_GB2312:KaiTi_GB2312

微軟正黑體:Microsoft JhengHei

微软雅黑体:Microsoft YaHei

装Office会生出来的一些:

隶书:LiSu

幼圆:YouYuan

华文细黑:STXihei

华文楷体:STKaiti

华文宋体:STSong

华文中宋:STZhongsong

华文仿宋:STFangsong

方正舒体:FZShuTi

方正姚体:FZYaoti

华文彩云:STCaiyun

华文琥珀:STHupo

华文隶书:STLiti

华文行楷:STXingkai

华文新魏:STXinwei

font-family,好看常用的字体

转载自http://www.zreading.cn/ican/2014/10/css-font-family/open in new window

例1(小米米官网):font-family: "Arial","Microsoft YaHei","黑体","宋体",sans-serif;

例2(淘宝技术研发中心):font: 12px/1.5 Tahoma,Helvetica,Arial,'宋体',sans-serif;

例3(加网 ):font: 14px/1.5 'Microsoft YaHei',arial,tahoma,\5b8b\4f53,sans-serif;

例4(淘宝UED):font: 12px/1 Tahoma,Helvetica,Arial,"\5b8b\4f53",sans-serif;

例5(一淘UX):font-family: Helvetica, 'Hiragino Sans GB', 'Microsoft Yahei', '微软雅黑', Arial, sans-serif;

引入字体

字体

@font-face {
    font-family: 'electronicFont';
    src: url("${ctxStatic}/map/arcgis4.x/images_new/LESLIEB_.TTF");
}

复选框大小

通过 设置属性 width和height 来控制大小

css pointer-events 设置元素是否对指针事件做出反应

<div style="pointer-events: none;">访问 <a href="https://www.w3school.com.cn/html/">a标签连接无法触发</a></div>

使用场景:例如 2个重叠的元素,由于其中一个元素在上,导致无法点中 下的元素

image-20220217101247767
image-20220217101247767
<input type="checkbox">
<span></span>
<span></span>

复选框中上面的 2条横梗,就是 通过span 显示出来的,但是点击 横线使无法触发 复选框的选中操作 所以此时

span{
    pointer-events:none;
}

19.9 案例

img
img
<div style="bottom:0px;position:fixed;height: 62px;z-index: 2147483647;padding: 7px;width: 100%;background-color: #FAFAFA;" ng-show="!!shareImgFlag">
	<div  style="width:33.333333333%;position:relative;;float:left;text-align: center;">
		<img src="img/ionic0022.png" width="30" height="30">
		<div style="text-align: center;">分享</div>
	</div>
	<div  style="width:33.333333333%;position:relative;;float:left;text-align: center;">
		<img src="img/ionic0023.png" width="30" height="30">
		<div style="text-align: center;">全选</div>
	</div>
	<div  style="width:33.333333333%;position:relative;;float:left;text-align: center;">
		<img src="img/ionic0020.png" width="30" height="30">
		<div style="text-align: center;">取消</div>
	</div>
</div>

19.10 html 定位

https://www.cnblogs.com/theWayToAce/p/5264436.htmlopen in new window

关于html中的定位(相对定位和绝对定位) position: relative; 和 position:absolute;

relative是根据父元素定位的.absolute则会找他的父元素,直到找到一个position属性不是static的父元素,可能是它的上一层,也可能是好几层,如果都没有定义position属性的话,那将根据body定位.还有一个区别是:relative的元素,不管你怎么改变top或是left,他原来的那一块div的位置还是存在着的,会占着那边.如果有人挤掉了那一块,那他的位置也会改变.如果是absolute的话,他就不占位置了,除非自己所定位的父元素产生改变,不然就不会改变.

例1:将d2放在d1的有上角 (绝对定位,将元素放在指定位置)

#d1{position:relative;}
#d2 {position: absolute;left: 30px;top: 20px;}

<div id="d1">
	<div id="d2"></div>
</div>

例2:在页面指定中增加一个图标(图片) 绝对定位

img{
	position:absolute;right:5%;top:5%;z-index:1;
	opacity:0.5;/*设置图片的透明度*/
}
  1. 浮动定位 float: left; 和float:right;

在div中设置几个元素,实现并排安放在指定位置

<div >
	<div style="width: 60%; float: left;">消息标题</div>
	<div style="width : 40%; float: left;">消息内容</div>
</div>

19.11 表单控件

  • 滑块控件 <input type="range" id="myRange">

    img
    img
  • 只读

    • 文本框等只读 readOnly="true"

    • 下拉选,时间选择插件 设置 disabled="true" 表单在提交时要将,disabled移除掉,,否则对应字段数据无效$("#status").removeAttr("disabled", true);

19.12 鼠标悬停事件

鼠标悬停图片放大(利用css方法)

<style type="text/css">
   img{  
		cursor: pointer;  
		transition: all 0.6s;  
	}  
	img:hover{  
		transition: all 1s ease 0s;  
		transform: scale(1.6);/*放大的倍数,所以在元素上要有图片的尺寸大小 。如:style="height:100px;width:100px;" */
	}
</style>

鼠标悬停修改图片src

.choose-menu:hover{
    backgroud-position:0 40px;
    transition:background-position 0.3s;
    content: url('${ctxStatic}/map/images/dmap/ionic020.png');
}
.choose-menu:visited{
    backgroud-position:0 0;
    transition:background-position 0.3s;
    content: url('${ctxStatic}/map/images/dmap/ionic020_1.png');
}

案例:动画效果 鼠标放到图片中 显示 标签

动画效果,通过 设置opacity 透明度,或高度、宽度 来达到隐藏显示效果,再加上 transition:1s; 添加点动态效果

.waterDiv{/*子项 先隐藏*/
    /*opacity是不透明度*/
    opacity: 0;/*先隐藏获取光标 显示*/
    width:0;
    height: 0;
    /*transition写在这里才是.yuan5常有的属性,无论出现还是消失都会有动画的效果*/
    transition:1s;
    overflow:hidden;/*如果圆圈中的数字超过区域就隐藏*/
}
.borderDiv:hover .waterDiv{
    /*如果将transition写在这里的话,只有当鼠标悬停在.yuan4上的时候才会有效果,
         当鼠标移出.yuan2的区域时,因为不出发hover的条件,所以消失的时候就没有变化效果了,
         结果就是瞬间消失*/
    opacity: 1;
    width:20px;
    height: 20px;
}
img
img

案例:关闭按钮,初始,隐藏,active 后 右移 显示,动画效果

.search-wrapper .close {
    position: absolute;
    z-index: 1;
    top:24px;
    right:20px;
    width:25px;
    height:25px;
    cursor: pointer;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    transform: rotate(-180deg);
    -webkit-transition: all .3s cubic-bezier(0.285, -0.450, 0.935, 0.110);
    -moz-transition: all .3s cubic-bezier(0.285, -0.450, 0.935, 0.110);
    transition: all .3s cubic-bezier(0.285, -0.450, 0.935, 0.110);
    -webkit-transition-delay: 0.2s;
    -moz-transition-delay: 0.2s;
    transition-delay: 0.2s;
    opacity: 0;
}
.search-wrapper.active .close {
    right:-50px;
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    transform: rotate(45deg);
    -webkit-transition: all .6s cubic-bezier(0.000, 0.105, 0.035, 1.570);
    -moz-transition: all .6s cubic-bezier(0.000, 0.105, 0.035, 1.570);
    transition: all .6s cubic-bezier(0.000, 0.105, 0.035, 1.570);
    -webkit-transition-delay: 0.5s;
    -moz-transition-delay: 0.5s;
    transition-delay: 0.5s;
    opacity: 1;
}

19.13动画:淡入,淡出

https://www.cnblogs.com/shark1100913/p/6266548.htmlopen in new window

https://www.html.cn/doc/css3/animations/index.htmlopen in new window

https://www.html.cn/doc/css3/transition/index.htmopen in new window

https://www.html.cn/doc/jquery/animate/open in new window

1.css 动画案例(静态图片,动画,上下动)

参考:https://blog.csdn.net/qq_16494241/article/details/78095575open in new window

<!DOCTYPE html>
<html>
 <head> 
  <meta charset="UTF-8" /> 
  <title>H5-test</title> 
  <style>

 
.arrow {
	width: 60px;
	height: 52px;
	color: #f00;
	font-size: 36px;
	position: absolute;
	left: 50%;
	margin-left: -30px;
	bottom: 0;
	-webkit-animation: fadeIn .5s 1s both ease-in-out;
	animation: fadeIn .5s 1s both ease-in-out;
}

.arrow div:first-child , .arrow div:last-child {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 60px;
	height: 40px;
	position: absolute;
	left: 0;
	-webkit-transform-origin: center top;
	transform-origin: center top;
}

.arrow div:first-child {
	top: 0;
	-webkit-animation: arrow .8s .5s ease-in-out infinite alternate;
	animation: arrow .8s .5s ease-in-out infinite alternate;
}

.arrow div:last-child {
	top: 12px;
	-webkit-animation: arrow .8s .8s ease-in-out infinite alternate;
	animation: arrow .8s .8s ease-in-out infinite alternate;
}

@-webkit-keyframes arrow {
	100% {
		-webkit-transform: translateY(-50%);
		opacity: 1;
	}

	0% {
		-webkit-transform: translateY(0);
		opacity: 0;
	}
}

@keyframes arrow {
	100% {
		transform: translateY(-50%);
		opacity: 1;
	}

	0% {
		transform: translateY(0);
		opacity: 0;
	}
}
</style> 
 </head> 
 <body> 
  <div class="arrow"> 
   <div> 
    <svg class="icon" style="width: 1em;height: 1em;vertical-align: middle;fill: currentColor;overflow: hidden;" viewbox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2859">
     <path d="M491.42 412.298c7.887 12.378 6.427 28.995-4.381 39.803L204.196 734.944l-90.51-90.51c-12.496-12.497-12.496-32.758 0-45.255L396.53 316.337l0.265 0.265 89.974-89.975c12.497-12.496 32.758-12.496 45.255 0l395.98 395.98-90.51 90.51c-12.497 12.497-32.758 12.497-45.255 0L491.42 412.297z" p-id="2860"></path>
    </svg> 
   </div> 
   <div> 
    <svg class="icon" style="width: 1em;height: 1em;vertical-align: middle;fill: currentColor;overflow: hidden;" viewbox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2859">
     <path d="M491.42 412.298c7.887 12.378 6.427 28.995-4.381 39.803L204.196 734.944l-90.51-90.51c-12.496-12.497-12.496-32.758 0-45.255L396.53 316.337l0.265 0.265 89.974-89.975c12.497-12.496 32.758-12.496 45.255 0l395.98 395.98-90.51 90.51c-12.497 12.497-32.758 12.497-45.255 0L491.42 412.297z" p-id="2860"></path>
    </svg> 
   </div> 
  </div>  
 </body>
</html>

css 动画 点击按钮 实现 显示隐藏

.turn_page:active{
            animation-name: example;
            animation-duration: 4s;
        }
        @keyframes example {
            0%   {opacity: 0;}
            25%  {opacity: 1;}
            50%  {opacity: 0.4;}
            100% {opacity: 1;}
        }

fadeOut() 方法使用淡出效果来隐藏被选元素,假如该元素是隐藏的。

fadeIn() 方法使用淡入效果来显示被选元素

$(selector).fadeOut(speed,callback)

speed可选。规定元素从可见到隐藏的速度。默认为 "normal"。

可能的值:

毫秒 (比如 1500)

"slow"

"normal"

"fast"

在设置速度的情况下,元素从可见到隐藏的过程中,会逐渐地改变其透明度(这样会创造淡出效果)。

案例:container.find('.result-container').fadeOut(100, function(){$(this).empty();});

  • transition: 设置动画,会和slideDown等一下jQuery 动画冲突,导致动画不生效

    //解决思路
    var $_element= $(".popup_div_temp").find(".popup_son_div");// popup_son_div
    $_element.hide();
    animationLoadHtml($_element);
    
    /**
    * 动画加载 元素
    *  针对  元素设置transition属性,和slideDown等一下jQuery 动画冲突,导致动画不生效 的场景
    * 动态加载的dom 对象,使用前 需要 先将其隐藏  $_element.hide();  然后获取高度、宽度,然后 使用动画 加载出
    * @param $_element :jQuery 对象 ($("#id"))
    */
    function animationLoadHtml($_element){
        var width = $_element.width();
        var height = $_element.height();
        $_element.css("height","0px");// 先将宽和高 设置为0 然后动态加载
        $_element.css("width","0px");
        $_element.show();
        $_element.animate({
            height:height+'px',
            width:width+'px',
            opacity:"1"
        },1000);
    }
    

    做动画常用到的几个 属性:放大,延迟

    transform: scale(1.2);
    transform-origin:left bottom;//把基准点修改为元素的左下角
    transition: all 0.6s;
    transition: all .5s cubic-bezier(0.000, 0.105, 0.035, 1.570); /*曲线*/
    transition-delay: 0.2s;/*延迟*/
    

    案例: 滚动,延迟,旋转,曲线

    search.html

    -webkit-transform: rotate(-180deg);
        -moz-transform: rotate(-180deg);
        transform: rotate(-180deg);
        -webkit-transition: all .3s cubic-bezier(0.285, -0.450, 0.935, 0.110);
        -moz-transition: all .3s cubic-bezier(0.285, -0.450, 0.935, 0.110);
        transition: all .3s cubic-bezier(0.285, -0.450, 0.935, 0.110);
        -webkit-transition-delay: 0.2s;
        -moz-transition-delay: 0.2s;
        transition-delay: 0.2s;
    
    
    
    
    
    /* 从左移到 右边*/
    .search-wrapper .input-holder .search-icon {
        width: 50px;
        height:50px;
        opacity: 1;
        border-radius:6px;
        background: #FFF;
        padding:0px;
        outline:none;
        position: relative;
        z-index: 2;
        float:right;
        cursor: pointer;
        transform: translate(-200px, 0px);/*初始 放在 最左侧*/
    
        -webkit-transition: all .6s cubic-bezier(0.285, -0.450, 0.935, 0.110);
        -moz-transition: all .6s cubic-bezier(0.285, -0.450, 0.935, 0.110);
        transition: all .6s cubic-bezier(0.285, -0.450, 0.935, 0.110);
    }
    .search-wrapper.active .input-holder .search-icon {
        transform: translate(0, 0px);
        -webkit-transition: all .6s cubic-bezier(0.285, -0.450, 0.935, 0.110);
        -moz-transition: all .6s cubic-bezier(0.285, -0.450, 0.935, 0.110);
        transition: all .6s cubic-bezier(0.285, -0.450, 0.935, 0.110);
        -webkit-transition-delay: 0.2s;
        -moz-transition-delay: 0.2s;
    

}




> html 修改图片src 动画

```js
function viewImg() {
    imgSrc = urlArr[nowIndex];
    var $this_ = $("#popup_detail_content_html_img");
    // 动画添加 src
    $this_.animate(
        {opacity:'toggle'},
        "slow",
        null,
        function(){
            $this_.attr("src",imgSrc);
            $this_.animate({opacity:'toggle'},"slow");
        }
  );

19.19图片作为按钮& 光标悬停

/* 按钮单击 效果*/
.title_button_img:hover{
	transform: scale(1.1);
	transition: all 0.6s;
}
/* 单击 */
.title_button_img:active {
    opacity: 0.1;
    transform: scale(1.1);
    transition: all 0.6s;
}

19.20 html部分知识

设置表格使表格的宽度上下自动对齐
td, th {
	display: table-cell;
	vertical-align: inherit;--------------vertical-align:属性设置元素的垂直对齐方式。inherit从父元素继承
}

8)表格中的 colspan 属性规定单元格可横跨的列数。
<tr>
	<td class="tit">编码设备:</td>
	<td colspan="3">
		<form:input path="deviceIds"/>
	</td>
</tr>
在用表格时,可以直接指定宽度 来优化
<th width="70%">消息标题</th>
<th width="30%" >消息时间</th>

19.25 滚动

需要注意parent_wrap 一定需要指定 高度,否则无法滚动

<div  style="overflow-y: hidden;height: 100%;">
	<div id="parent_wrap" class="parent_wrap" style="overflow-y: auto;height: 100%;">
        <p class="content1">内容滚动。。。。。。。。</p>
        <p class="content2">内容滚动。。。。。。。。</p>
        <p class="content3">内容滚动。。。。。。。。</p>
    </div>
</div>

自定义滚动条

::-webkit-scrollbar {
    width: 8px;
    height: 8px;
    background-color: #e4e4e4;
    border-radius: 6px;
}
::-webkit-scrollbar-thumb {
    background-color: #8291A9;
    border-radius: 6px;
}

谷歌

::-webkit-scrollbar {
  background: #f7f7f9;
  width: .08rem;  /* 纵向滚动条滑块宽度 */
  height: .09rem; /* 横向滚动条滑块宽度 */
}
::-webkit-scrollbar-track-piece { /*滚动条背景颜色*/
  background: #f7f7f9;
}
::-webkit-scrollbar-thumb { /* 滑块 */
  border-radius: .1rem;
  background: #e5e5e5;
}
// 也可以单独设置横向滚动条和纵向滚动条的背景颜色
::-webkit-scrollbar-thumb:vertical { /* 纵向滑块 */
  background: #e5e5e5;
}
::-webkit-scrollbar-thumb:horizontal { /* 横向滑块 */
  background: #e5e5e5;
}


对应 父容器 需要添加 属性 overflow: auto;和高度宽度 超出父容器部分隐藏,显示 滚动条

  • 场景1 :使用过,但是没测试过x轴上的滚动样式
/*如果使用百分比,则需要定义父节点宽度,高度,如果父节点高度和宽度也是使用百分比,那么需要找到爷爷节点,设置高度、宽度,总知,一定要定义父节点高宽,不能通过子元素把父节点撑起来而获取的高度、宽度*/
.scroll_zdy {
	width: 100px;
	height: 100px;  
	overflow: auto; 
}
.scroll_zdy::-webkit-scrollbar {/*滚动条整体样式*/
    width: 4px;     /*Y轴滚动条 尺寸   如果想实现 不出现滚动条并且 可以滚动 设置宽度为0*/
    height: 4px;/* 水平滚动条 */
}
.scroll_zdy::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
    background: #535353;
}
.scroll_zdy::-webkit-scrollbar-track {/*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
    border-radius: 10px;
    background: #EDEDED;
}

说明:滚动条组成部分

  1. ::-webkit-scrollbar 滚动条整体部分

  2. ::-webkit-scrollbar-thumb 滚动条里面的小方块,能向上向下移动(或向左向右移动)

  3. ::-webkit-scrollbar-track 滚动条的轨道(里面装有Thumb)

  4. ::-webkit-scrollbar-button 滚动条的轨道的两端按钮,由于通过点击微调小方块的位置。

  5. ::-webkit-scrollbar-track-piece 内层轨道,滚动条中间部分

  6. ::-webkit-scrollbar-corner 边角,即垂直滚动条和水平滚动条相交的地方

  7. ::-webkit-resizer 两个滚动条的交汇处上用于拖动调整元素大小的小控件

img
img

其他设置项:

:horizontal      //horizontal伪类适用于任何水平方向上的滚动条 

:vertical        //vertical伪类适用于任何垂直方向的滚动条 

:decrement      //decrement伪类适用于按钮和轨道碎片。表示递减的按钮或轨道碎片,例如可以使区域向上或者向右移动的区域和按钮 

:increment      //increment伪类适用于按钮和轨道碎片。表示递增的按钮或轨道碎片,例如可以使区域向下或者向左移动的区域和按钮 

:start         //start伪类适用于按钮和轨道碎片。表示对象(按钮 轨道碎片)是否放在滑块的前面 

:end       //end伪类适用于按钮和轨道碎片。表示对象(按钮 轨道碎片)是否放在滑块的后面 

:double-button //double-button伪类适用于按钮和轨道碎片。判断轨道结束的位置是否是一对按钮。也就是轨道碎片紧挨着一对在一起的按钮。 

:single-button //single-button伪类适用于按钮和轨道碎片。判断轨道结束的位置是否是一个按钮。也就是轨道碎片紧挨着一个单独的按钮。 

:no-button  //no-button伪类表示轨道结束的位置没有按钮。 

:corner-present  //corner-present伪类表示滚动条的角落是否存在。 

:window-inactive  //适用于所有滚动条,表示包含滚动条的区域,焦点不在该窗口的时候。 

::-webkit-scrollbar-track-piece:start { 
	/*滚动条上半边或左半边*/ 
} 
::-webkit-scrollbar-thumb:window-inactive { 
	/*当焦点不在当前区域滑块的状态*/ 
} 
::-webkit-scrollbar-button:horizontal:decrement:hover {>  
	/*当鼠标在水平滚动条下面的按钮上的状态*/ 
}
滚动条的设置
1. ::-webkit-scrollbar 滚动条整体部分,可以设置宽度等
2. ::-webkit-scrollbar-button 滚动条两端的按钮
3. ::-webkit-scrollbar-track  外层轨道
4. ::-webkit-scrollbar-track-piece  内层滚动槽
5. ::-webkit-scrollbar-thumb 滚动的滑块
6. ::-webkit-scrollbar-corner 边角
7. ::-webkit-resizer 定义右下角拖动块的样式
image-20201126094257366
image-20201126094257366
::-webkit-scrollbar :滚动条整体部分,其中的属性: width,height,background,border等。

::-webkit-scrollbar-button :滚动条两端的按钮。可以用display:none让其不显示,也可以添加背景图片,颜色改变显示效果。

::-webkit-scrollbar-track :外层轨道。可以用display:none让其不显示,也可以添加背景图片,颜色改变显示效果。

::-webkit-scrollbar-track-piece :内层轨道,具体区别看下面gif图,需要注意的就是它会覆盖第三个属性的样式。

::-webkit-scrollbar-thumb :滚动条里面可以拖动的那部分

::-webkit-scrollbar-corner :边角,两个滚动条交汇处

::-webkit-resizer :两个滚动条交汇处用于拖动调整元素大小的小控件(基本用不上)
image-20201126094403133
image-20201126094403133

案例

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>标题</title>
    <style>
        div {
            width: 100px;
            height: 300px;
            border: 2px solid red;
            overflow-x: scroll;
            overflow-y: scroll;
        }

        /* 设置滚动条的样式 */
        ::-webkit-scrollbar {
        width:12px;
        background-color: aqua;
        }

        /* 滚动槽 */
        ::-webkit-scrollbar-track {
        border-radius:10px;
        }

        /* 滚动条滑块 */
        ::-webkit-scrollbar-thumb {
        border-radius:10px;
        background:black;
        }


    </style>

    </script>
</head>
<body>

<div id="div1">
    请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。小天地,大世界是一个Web前端的技术博客。 主要是关于HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还包含一些PHP语言等的实用例子。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。小天地,大世界是一个Web前端的技术博客。 主要是关于HTML 5,CSS 3,
    JavaScript,JQuery等。除此之外,还包含一些PHP语言等的实用例子。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。小天地,大世界是一个Web前端的技术博客。 主要是关于HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还包含一些PHP语言等的实用例子。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。
    小天地,大世界是一个Web前端的技术博客。 主要是关于HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还包含一些PHP语言等的实用例子。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。小天地,大世界是一个Web前端的技术博客。 主要是关于HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还包含一些PHP语言等的
    实用例子。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。小天地,大世界是一个Web前端的技术博客。 主要是关于HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还包含一些PHP语言等的实用例子。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。小天地,大世界是一个Web前端的技术博客。 主要是关于HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还
    包含一些PHP语言等的实用例子。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。小天地,大世界是一个Web前端的技术博客。 主要是关于HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还
    包含一些PHP语言等的实用例子。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。小天地,大世界是一个Web前端的技术博客。 主要是关于
    HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还包含一些PHP语言等的实用例子。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。
    小天地,大世界是一个Web前端的技术博客。 主要是关于HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还包含一些PHP语言等的实用例子。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。
    小天地,大世界是一个Web前端的技术博客。 主要是关于请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。请选择Webkit内核的浏览器才可以正常的看到滚动条的变化。
    小天地,大世界是一个Web前端的技术博客。 主要是关于
    HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还
     包含一些PHP语言等的实用例子。
    小天地,大世界是一个Web前端的技术博客。 主要是关于
    HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还
     包含一些PHP语言等的实用例子。
    HTML 5,CSS 3,JavaScript,JQuery等。除此之外,还
     包含一些PHP语言等的实用例子。
</div>

</body>
</html>

使用总结

<div class="scroll_zdy"><!--设置 滚动条,需要定义高度和宽度 -->
	<div id="scroll_content" class="scroll" style="transform: translate3d(0px, -43px, 0px) scale(1);"><!-用于后面可能涉及的 位置移动,翻页等 -->
		<div>内容</div>
		<div>内容</div>
		<div>内容</div>
	</div>
</div>	
<!-- 使用说明 父节点 定义宽高,可有出现滚动条,但是 在 父节点和 内容区域中 又添加一个div 是考虑,如果有场景需要自动翻页,那么 就需要动 这个id="scroll_content" 的位置,通过设置其位置,来实现 移动和翻页  -->

火狐

* {
  scrollbar-color: #e5e5e5 #f7f7f9; /* 滑块颜色  滚动条背景颜色 */
  scrollbar-width: thin; /* 滚动条宽度有三种:thin、auto、none */
}

隐藏滚动条

.tab-item__content {
    overflow-x: auto;
    &::-webkit-scrollbar {
        width: 0;
        height: 0px;
    }
}

19.30 背景图片 background-image

CSS让DIV按照背景图片的比例缩放,并让背景图片填充整个元素(转)

background-size: 100% auto; 
background-repeat: no-repeat; 
background-image: url(../images/aaa.png); 
background: url(/CPMS/static/images/screen/changeimage/搜索框.png) no-repeat center;
background-size:100%100%;/*可以让 背景图片完全填充*/
background-size:cover;/*自动填充,比 background-size:100%100%; 更合理*/
background-position: 10% 50%;  /* 背景图像从容器的 10% 水平和 50% 垂直位置开始 */

说明: background:url(图片) no-repeat right center不明白是什么意思,百度以后学习到了,在此记载知识点;

这一行代码其实是背景图定义形式的简写 完整形式是:

background-image:url(图片); background-repeat:no-repeat; background-position:right center

right center是设置图片的初始位置,right是在水平方向上贴容器或浏览器页面的右侧,center是在垂直方向上居中,这两个的顺序是先定义水平位置,再定义垂直位置;

案例:

.right_popup{
    background: url(../map/3DmapImages/ionic_bg_006_02.png) no-repeat center;
    background-size: 100%100%;
    width:621px;
    height:893px;
}

案例:背景图片不重复,在水平方向靠近容器的右侧,在垂直方向距离容器上方14px

background:url(../images/top_ico.png) no-repeat right 14px;

标签是用于定义列表项目。这行代码意思是每一列包含的背景图片是top_ico.png,图片不重复,靠近列表容器的右侧,距离列表容器上方20px;

.top_menu li { float:left; background:url(../images/top_ico.png) no-repeat right 20px;

背景:【背景图片链接】【平铺方式(无平铺)】【距左边边距(数值或left或百分比)】【距顶端边距(数值或top或百分比)】

background:url(../images/nav_bg.png) no-repeat -20px -150px;

案例图片作为 按钮

.HomeButton .home {
    padding: 2px;
    width: 30px;
    height: 30px;
    background-color: #666;
    background-color: rgba(102,102,102,0.80);
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    /* user-select: none; */
    cursor: pointer;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    -o-border-radius: 5px;
    border-radius: 5px;
    background-image: url(../dijit/images/home.png);
    background-position: center center;
    background-repeat: no-repeat;
}
.HomeButton .home:hover {
    background-color: #333;
    background-color: rgba(102,102,102,0.90);
}

.HomeButton .home:active {
	background-color: #ccc;
	background-color: rgba(102,102,102,0.60);
}

.HomeButton .loading {
	background-image: url("../dijit/images/home-spinner.gif");
}

19.41 图片加载失败 onerror

<img id="img_{{item.id}}" class="wh100" src="{{item.filepathSmall}}" onerror="this.src='${ctxStatic}/images/jkzx/zanwutupian.png'" >

19.40 遮罩效果

参考网址:https://www.cnblogs.com/aspx-net/archive/2011/03/11/1981071.htmlopen in new window

在页面内先定义好需要显示的DIV和遮罩层的CSS,然后用在onclick事件时,通过JS去控制两个DIV的样式:display='block' or display='none'.就可以实现DIV的显示和隐藏。注意两个DIV的z-index,显示在最上面的DIV的z-index一定要比遮罩层的z-index大。

思路: 在父页面和弹出层中 添加一层,铺满 父页面,设置 透明度,设置颜色,即为 遮罩层,通过对遮罩层的显示和隐藏从而达到,这种遮罩效果

<!DOCTYPE html>
 <html>
<head>
<title>DIV CSS遮罩层</title>
<script language="javascript" type="text/javascript">
		function showdiv() {            
            document.getElementById("bg").style.display ="block";
            document.getElementById("show").style.display ="block";
        }
		function hidediv() {
            document.getElementById("bg").style.display ='none';
            document.getElementById("show").style.display ='none';
        }
</script>
<style type="text/css">
     #bg{ 
        display:none;
        position:absolute;
        top:0%;left:0%;width:100%;
        height:100%;
        background-color:black;
        z-index:1001;
        -moz-opacity:0.7;
        opacity:.70;
        filter:alpha(opacity=70);
    }
    #show{display:none;
        position:absolute;top:25%;left:22%;
        width:53%;height:
        49%;padding:8px;
        border:8pxsolid#E8E9F7;
        background-color:white;z-index:1002; 
        overflow: auto;
    }
</style>
</head>
<body>
<input id="btnshow" type="button" value="Show" onclick="showdiv();"/>
<div id="bg"></div>    <!-- 遮罩层  -->
<div id="show">测试
    <input id="btnclose" type="button" value="Close" onclick="hidediv();"/>
</div>
</body>
</html>

19.41css-图片闪烁效果

按钮 点击效果

/* 动画 可以 作为 图片按钮 */
.img_button:hover{
    transform: scale(1.1);
    transition: all 0.6s;
}
.img_button:active{
    animation-name: example;
    animation-duration: 4s;
}
@keyframes example {
    0%   {opacity: 0;}
    25%  {opacity: 1;}
    50%  {opacity: 0.4;}
    100% {opacity: 1;}
}

css-图片闪烁效果

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <title>呼吸灯</title>
    <style type="text/css">
    /* css代码 */
    .breath_light {
    /*width: 300px;  */                                  /* 宽度 */
    /*height: 300px; */                                   /* 高度 */
    /*border:#666 1px solid;*/
    /*border-radius:50%;*/
    opacity: 0.1;                                   /* 不透明度 */
    overflow: hidden;                               /* 溢出隐藏 */
    background:#FF3;                            /* 背景色 */
   /* margin: 25% auto; */                              /* 外边距 */
  
    /* IE10、Firefox and Opera,IE9以及更早的版本不支持 */
    animation-name: breath;                         /* 动画名称 */
    animation-duration: 700ms;                         /* 动画时长3秒 */
    animation-timing-function: ease-in-out;         /* 动画速度曲线:以低速开始和结束 */
    animation-iteration-count: infinite;            /* 播放次数:无限 */
 
    /* Safari and Chrome */
    -webkit-animation-name: breath;                 /* 动画名称 */
    -webkit-animation-duration: 700ms;                 /* 动画时长3秒 */
    -webkit-animation-timing-function: ease-in-out; /* 动画速度曲线:以低速开始和结束 */
    -webkit-animation-iteration-count: infinite;    /* 播放次数:无限 */
}
 
@keyframes breath {
    from { opacity: 0.1; }                          /* 动画开始时的不透明度 */
    50%  { opacity:   1; }                          /* 动画50% 时的不透明度 */
    to   { opacity: 0.1; }                          /* 动画结束时的不透明度 */    
}
 
@-webkit-keyframes breath {
    from { opacity: 0.1; }                          /* 动画开始时的不透明度 */
    50%  { opacity:   1; }                          /* 动画50% 时的不透明度 */
    to   { opacity: 0.1; }                          /* 动画结束时的不透明度 */
}
    </style>
</head>
<body>
    <div  title="呼吸灯">
        <img class="breath_light" src="../img/guihui.jpg" style="height: 60px;width: 60px;" />
    </div>
</body>
</html>

19.42使用CSS实现按钮点击波纹效果

主要借助::after伪类及CSS3中的transform和transition属性:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">

<div class="container text-center">
        <button class="btn btn-default ripple btn-lg">Button</button>
        <button class="btn btn-default ripple btn-lg">Button with very long content</button>
</div>
<!--实现1 -->
<style>
.ripple {
    position: relative;
    //隐藏溢出的径向渐变背景
    overflow: hidden;
}

.ripple:after {
    content: "";
    display: block;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    pointer-events: none;
    //设置径向渐变
    background-image: radial-gradient(circle, #666 10%, transparent 10.01%);
    background-repeat: no-repeat;
    background-position: 50%;
    transform: scale(10, 10);
    opacity: 0;
    transition: transform .3s, opacity .5s;
}

.ripple:active:after {
    transform: scale(0, 0);
    opacity: .3;
    //设置初始状态
    transition: 0s;
}

</style>
<!-- 实现2-->
<style>
.ripple {
    position: relative;
    //此处不需要设置overflow:hidden,因为after元素需要溢出显示
}
.ripple:focus{
    outline: none;
}

.ripple:after {
    content: "";
    display: block;
    position: absolute;
    //扩大伪类元素4个方向各10px
    top: -10px;
    left: -10px;
    right: -10px;
    bottom: -10px;
    pointer-events: none;
    background-color: #333;
    background-repeat: no-repeat;
    background-position: 50%;
    opacity: 0;
    transition: all .3s;
}

.ripple:active:after {
    opacity: .3;
    //设置初始状态
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    transition: 0s;
}


</style>

19.50 Table

设置时 宽度设置不了 ,,老是挤下个元素(强制换行)

设置属性 tyle="WORD-WRAP: break-word" 如果还是不换行 那么再设置 宽度: <td style="WORD-WRAP: break-word" width="500"></td>

<div style="font-size: 11px;color:#868686;white-space:normal;word-wrap:break-word;word-break:break-all;" ></div>

table 设置隔行不同色

table tr:nth-child(odd){background: #ccc;}/*奇数行背景*/
table tr:nth-child(even){background: #ccc;}/*偶数行背景*/

19.55 超长字符(限定文字长度)

限定字符串长度列表展示数据太长 可以用省略号“......”(隐藏信息) 限定长度(限定字符串长度)

用法 :自定义标签${fns:abbr(字段,14)} 案例:·${fns:abbr(task.rwdName,15)}`

自定义标签: -----------------------------------------------------------参考5.案例四

自定义标签

<function>
	<description>缩写字符串,超过最大宽度用“...”表示</description>
	<name>abbr</name>
	<function-class>cn.semdo.common.utils.StringUtils</function-class>
	<function-signature>java.lang.String abbr(java.lang.String, int)</function-signature>
	<example>${fns:abbr(str,length)}</example>  
</function>

对应app上也有 {{item.fxbxStr|limitTo:20}}

css 控制,超出容器 用省略号

p {
	width:90%;
	overflow:hidden;/* 滚动条隐藏 */
	white-space:nowrap;/*规定段落中的文本不进行换行*/
	text-overflow:ellipsis;/*属性规定当文本溢出包含元素时发生的事情*/
}

自动换行:

.autoline-element{
            white-space:normal;
            word-wrap:break-word;
            word-break:break-all
        }

white-space: normal|pre|nowrap|pre-wrap|pre-line|inherit;

  • white-space: 属性设置如何处理元素内的空白

    normal: 默认。空白会被浏览器忽略。 pre:空白会被浏览器保留。其行为方式类似 HTML 中的 pre 标签。 nowrap: 文本不会换行,文本会在在同一行上继续,直到遇到 br标签为止。 pre-wrap: 保留空白符序列,但是正常地进行换行。 pre-line: 合并空白符序列,但是保留换行符。 inherit: 规定应该从父元素继承 white-space 属性的值。 word-wrap: normal|break-word;

  • word-wrap: 属性用来标明是否允许浏览器在单词内进行断句,这是为了防止当一个字符串太长而找不到它的自然断句点时产生溢出现象。

    normal: 只在允许的断字点换行(浏览器保持默认处理) break-word: 在长单词或URL地址内部进行换行 word-break: normal|break-all|keep-all;

  • word-break 属性用来标明怎么样进行单词内的断句。

    normal:使用浏览器默认的换行规则。 break-all:允许再单词内换行 keep-all:只能在半角空格或连字符处换行

css实现文字从右向左排列

在css样式中加入:direction: rtl ,即可让文字从右向左排列,但此时符号的排列位置不正确,会显示在文本的最左边。

如:hello,world! 会变成:!hello,world

解决方式

1、在文本的末尾加入特殊符号 “ &#x200E ”

<div class="container">Hello, World!&#x200E;</div>

2、使用行内元素(span)包裹着文本,并且为内联元素设置样式:

<html>
  <head>
    <style type="text/css">
      div.container
      {
      	direction: rtl;
      }
      .text {/*有的地方不加这个会出现异常*/
      	direction: ltr;
        unicode-bidi: bidi-override;
      }
    </style>
  </head>
  <body>
    <div class="container">
     <span class="text">Hello, World!</span>
    </div>
  </body>
</html>

19.60 自定义输入框样式

.style2 {
		  border: 1px solid #cccccc;
		  display: inline-block;
		  height: 20px;
		  padding: 4px 6px;
		  margin-bottom: 10px;
		  font-size: 14px;
		  line-height: 20px;
		  color: #555555;
		  vertical-align: middle;
		  -webkit-border-radius: 4px;
		     -moz-border-radius: 4px;
		          border-radius: 4px;
		}

19.250 文件竖向排版

方法一:使用 换行标签

方法二:设置文字外框DIV的宽度,让文本自动换行

方法三:设置CSS属性样式 writing-mode:tb-rl

19.260 辅助开发,给div添加 边框导致换行

/* 辅助开发,定位边框*/
.bk{
    border: 1px solid #ccc;
    box-sizing: border-box;/*定义边框内收 ,防止 超出父容器*/
}

19.270 table 最好定义 <thead> <tbody> 来区分 内容和标题

场景:table 如果内容为空会导致 标题 跑到内容的区域

<table id="period_table" style="height: 285px;">
    <thead>/*标题*/
        <tr style="height: 48px;">
            <th style="width: 20%;" >项目</th>
            <th style="width: 28%;" >上次检测</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach items="${data.periodJsonArr}" var="periodJson" varStatus="indexItem">
            <tr style="height: 58px;" id="period_${indexItem.index}" class="need_hover">
                <td>${periodJson.period_name}</td>
                <td>${periodJson.period_time}</td>
            </tr>
        </c:forEach>
    </tbody>
</table>
image-20200915170754721
image-20200915170754721

19.280

19.290 进度条

<progress id="myProgress" value="75" max="100"></progress>

动画: transition: width 1s ease 0.3s; 可以支持进度条动画改变

css自定义进度条

<style>
.zdy_progress{
    display: flex;
    align-items: center;
}
/* 自定义进度条*/
.zdy_progress .review{
    color: #777;
    display: flex;
    font-size: 12px;
    align-items: center;
    height: 11px;
    width: 200px;
    padding: 10px;
    margin: 5px 0;
}
.zdy_progress .progress{
    background-color: rgba(100, 100, 100);
    border-radius: 5px;
    position: relative;
    margin: 0 10px;
    width: 100%;
    height: 100%;
}
.zdy_progress .progress-done{
	background: linear-gradient(to left, rgb(242, 112, 156), rgb(255, 148, 114));
    box-shadow: 0 3px 3px -5px rgb(242, 112, 156), 0 2px 5px rgb(242, 112, 156);
    border-radius: 5px;
    height: 10px;
    width: 0;
    transition: width 1s ease 0.3s;
}
</style>
<div class="zdy_progress" style="with:120px;">
    <div class="review">
		<span class="icon-container">5 <i class="fas fa-star"></i></span>
		<div class="progress">
			<div class="progress-done" data-done="68" style="width: 68%;"></div>
		</div>
		<span class="percent">68%</span>
	</div>
</div>

19.295

<!DOCTYPE html>
<html>
	<head>
		    
		<meta name="viewport" content="width=device-width, initial-scale=1">
		    
		<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
		    
		<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js">
		</script>
		    
		<style>
			         body {
	font-size:12px;
}
ul li {
	list-style:none;
}
.track-rcol {
	width:100%;
	border:1px solid #eee;
}
.track-list {
	margin:20px;
	padding-left:5px;
	position:relative;
}
.track-list li {
	position:relative;
	padding:9px 0 0 25px;
	line-height:18px;
	border-left:1px solid #d9d9d9;
	color:#999;
}
.track-list li.first {
	color:red;
	padding-top:0;
	border-left-color:#fff;
}
.track-list li .node-icon {
	position:absolute;
	left:-6px;
	top:50%;
	width:11px;
	height:11px;
	border:1px solid #ccc;
	border-radius:50%;
	background:#ccc;
}
.track-list li.first .node-icon {
	background-position:0 -72px;
}
.track-list li .time {
	margin-right:20px;
	position:relative;
	top:4px;
	display:inline-block;
	vertical-align:middle;
}
.track-list li .txt {
	position:relative;
	top:4px;
	display:inline-block;
	vertical-align:middle;
}
.track-list li.first .time {
	margin-right:20px;
}
.track-list li.first .txt {
	max-width:600px;
}

		</style>
	</head>
	<body>
		    
		<div class="track-rcol">
			<div class="track-list">
				<ul>
					<li class="first">
						<i class="node-icon">
						</i>
						<span class="time">
							2016-03-10 18:07:15
						</span>
						<span class="txt">
							感谢您在京东购物,欢迎您再次光临!
						</span>
					</li>
					<li>
						<i class="node-icon">
						</i>
						<span class="time">
							2016-03-10 18:07:15
						</span>
						<span class="txt">
							【京东到家】京东配送员【申国龙】已出发,联系电话【18410106883,感谢您的耐心等待,参加评价还能赢取京豆呦】
						</span>
					</li>
					<li>
						<i class="node-icon">
						</i>
						<span class="time">
							2016-03-10 18:07:15
						</span>
						<span class="txt">
							感谢您在京东购物,欢迎您再次光临!
						</span>
					</li>
					<li>
						<i class="node-icon">
						</i>
						<span class="time">
							2016-03-10 18:07:15
						</span>
						<span class="txt">
							感谢您在京东购物,欢迎您再次光临!
						</span>
					</li>
					<li>
						<i class="node-icon">
						</i>
						<span class="time">
							2016-03-10 18:07:15
						</span>
						<span class="txt">
							感谢您在京东购物,欢迎您再次光临!
						</span>
					</li>
					<li>
						<i class="node-icon">
						</i>
						<span class="time">
							2016-03-10 18:07:15
						</span>
						<span class="txt">
							感谢您在京东购物,欢迎您再次光临!
						</span>
					</li>
				</ul>
			</div>
		</div>
	</body>

</html>

19.300 tab

<style>
	/*tab页切换*/
    .tabMenuBox{
        font-size: 24px;
        padding: 20px;
        color: #fff;
    }
    .tabMenuBox ul li {
        text-align: center;
        line-height: 35px;
    }
    /*默认*/
    .tabLi {
        width: 25%;
        float: left;
        border-bottom-style: solid;
        border-width: 2px;
        border-color: #74b7b4;
    }
    /*激活*/
    .tabActive {
        border-color: #fff;
    }
    li {
        list-style: none;
    }
</style>
<script>
	//点击tab 清除历史选中的tab页
    function  tabSwitch(type){
        $(".clearfix li").each(function(i){
            $(this).removeClass('tabActive');
        });
        $("#listType"+type).addClass("tabActive");
    }
</script>

<div class="tabMenuBox">
    <ul class="clearfix">
        <li id="listType1" class="tabLi tabActive" onclick="tabSwitch('1')"><span>tab1</span></li>
        <li id="listType2" class="tabLi" onclick="tabSwitch('2')"><span>tab2</span></li>
        <li id="listType3" class="tabLi" onclick="tabSwitch('3')"><span>tab3</span></li>
        <li id="listType4" class="tabLi" onclick="tabSwitch('4')"><span>tab4</span></li>
    </ul>
</div>
  • 横向tab + 滚动
image-20210407085712920
image-20210407085712920
<div class="top-pos">
    <div id="gesturesButton" class="bq-head" >
        <img src="modules/dsj/img/zk.png" height="7px;"><!-- 上滑,下滑按钮 -->
    </div>
    <!-- 表头tab,支持横向滚动 -->
    <ion-scroll id="head_tab" zooming="true" direction="x"  class="head_container">
        <div class="head_li tabActive" ng-click="tabSwitch('gttz',$event)">GT台账</div>
        <div class="head_li" ng-click="tabSwitch('tqqk',$event)">天气情况</div>
        <div class="head_li" ng-click="tabSwitch('jksk',$event)">交跨/三跨</div>
        <div class="head_li" ng-click="tabSwitch('wrjxs',$event)">无人机巡视</div>
        <div class="head_li" ng-click="tabSwitch(1,$event)">线路信息</div>
        <div class="head_li" ng-click="tabSwitch(1,$event)">线路信息</div>
        <div class="head_li" ng-click="tabSwitch(1,$event)">线路信息</div>
        <div class="head_li" ng-click="tabSwitch(1,$event)">线路信息</div>
        <div class="head_li" ng-click="tabSwitch(1,$event)">线路信息</div>
        <div class="head_li" ng-click="tabSwitch(1,$event)">线路信息</div>
        <div class="head_li" ng-click="tabSwitch(1,$event)">线路信息</div>
    </ion-scroll>
</div>

<style>
    .top-pos {
        /*  position: absolute;
        top: 0px; */
        width: 100%;
        z-index: 99999998;
    }
    .head_container{
        width: 100%;
        overflow-x: scroll;
        overflow-y: hidden;
        white-space: nowrap;
        background-color: #fff;
        padding: 0 10px;
        box-sizing: border-box;
    }
    .head_li {
        width: 73px !important;
        margin: auto;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: 400;
        color: #8C8C8C;
        flex-shrink: 0;
        height: 32px;
    }

    .tabActive {
        border-bottom: 1.5px #2094FF solid;
        color: #000000;
    }
</style>
<script>
	//点击tab 清除历史选中的tab页
	$scope.tabSwitch=function(type,$event){
        $(".head_li").each(function(i){
            $(this).removeClass('tabActive');
        });
        if($event==undefined){
        	$(".head_li").eq(0).addClass("tabActive");
        }
        $($event.target).addClass("tabActive");
        $event.stopPropagation();//冒泡
      }
</script>

19.341 子元素横向排列,超过父容器宽度不换行纯css方法

  • inline-block方法
ul{
  white-space:nowrap;
  font-size:0;
}
li{
  display:inline-block;
}
  • flex方法
ul{
  display:flex;
}
li{
  flex-shrink:0;
}

19.310 响应式布局

思路是 讲页面宽度 分层 12分

<html>
    </head>
        <style>/*响应式布局*/
            * {
                box-sizing: border-box;
            }
            .row:after {
                content: "";
                clear: both;
                display: block;
            }
            [class*="col-"] {
                float: left;
            }
            .col-1 {width: 8.33%;}
            .col-2 {width: 16.66%;}
            .col-3 {width: 25%;}
            .col-4 {width: 33.33%;}
            .col-5 {width: 41.66%;}
            .col-6 {width: 50%;}
            .col-7 {width: 58.33%;}
            .col-8 {width: 66.66%;}
            .col-9 {width: 75%;}
            .col-10 {width: 83.33%;}
            .col-11 {width: 91.66%;}
            .col-12 {width: 100%;}

        </style>
    </head>
<body>

    <div class="row">
        <div class="col-3">第一块</div>
        <div class="col-9">第二块</div>
    </div>
</body>
</html>

CSS3 @media 查询open in new window


19.瀑布流

https://www.jb51.net/html5/691874.htmlopen in new window

案例1.**JS 实现瀑布流 [JS 实现瀑布流.html](D:\java编程\笔记\html\图片展示&瀑布流\自定义瀑布流\JS 实现瀑布流.html) **

思路分析

  • 瀑布流布局的特点是等宽不等高。
  • 为了让最后一行的差距最小,从第二行开始,需要将图片放在第一行最矮的图片下面,以此类推。
  • 父元素设置为相对定位,图片所在元素设置为绝对定位。然后通过设置 top 值和 left 值定位每个元素。
<!DOCTYPE html>
<html>
<head>
    <style>
		
        .box {
            width: 100%;
            position:relative;
        }
        .item {
            position: absolute;
        }
        .item img{
            width: 100%;
            height:100%;
        }
    </style>
</head>
<body>
<div class="box">
    <div class="item">
        <img  src="./1.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./2.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./3.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./4.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./5.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./6.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./7.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./8.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./9.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./10.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./11.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./12.jpg" alt="" />
    </div>
</div>
</body>
<script src="jquery.min.js"></script>
<script>
    function waterFall() {
        // 1 确定图片的宽度 - 滚动条宽度
        var pageWidth = getClient().width-8;
        var columns = 3; //3列
        var itemWidth = parseInt(pageWidth/columns); //得到item的宽度
        $(".item").width(itemWidth); //设置到item的宽度
        var arr = [];
        $(".box .item").each(function(i){
            var height = $(this).find("img").height();
            if (i < columns) {
                // 2 第一行按序布局
                $(this).css({
                    top:0,
                    left:(itemWidth) * i+20*i,
                });
                //将行高push到数组
                arr.push(height);
            } else {
                // 其他行
                // 3 找到数组中最小高度  和 它的索引
                var minHeight = arr[0];
                var index = 0;
                for (var j = 0; j < arr.length; j++) {
                    if (minHeight > arr[j]) {
                        minHeight = arr[j];
                        index = j;
                    }
                }
                // 4 设置下一行的第一个盒子位置
                // top值就是最小列的高度
                $(this).css({
                    top:arr[index]+30,//设置30的距离
                    left:$(".box .item").eq(index).css("left")
                });

                // 5 修改最小列的高度
                // 最小列的高度 = 当前自己的高度 + 拼接过来的高度
                arr[index] = arr[index] + height+30;//设置30的距离
            }
        });
    }
    //clientWidth 处理兼容性
    function getClient() {
        return {
            width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
            height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
        }
    }
    // 页面尺寸改变时实时触发
    window.onresize = function() {
        //重新定义瀑布流
        waterFall();
    };
    //初始化
    window.onload = function(){
        //实现瀑布流
        waterFall();
    }
</script>
</html>

案例2. column 多行布局实现瀑布流

思路分析: column多行布局实现瀑布流.html

column 实现瀑布流主要依赖两个属性。 一个是 column-count 属性,是分为多少列。 一个是 column-gap 属性,是设置列与列之间的距离。

​ column-width 属性 ,设置列宽

案例1和2 合理 长度不会超出父容器

<!DOCTYPE html>
<html>
<head>
    <style>
        .box {
            margin: 10px;
            column-count: 3;
            column-gap: 10px;
            /*column-width: 250px;  列的宽度 */
        }
        .item {
            margin-bottom: 10px;
        }
        .item img{
            width: 100%;
            height:100%;
        }
    </style>
</head>
<body>
<div class="box">
    <div class="item">
        <img  src="./1.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./2.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./3.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./4.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./5.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./6.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./7.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./8.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./9.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./10.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./11.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./12.jpg" alt="" />
    </div>
</div>
</body>
也可以直接设置 每列的宽度 
.container {
		column-width: 250px;/* 列的宽度 */
		column-gap: 5px; /* 列的间距 */
	}

flex 弹性布局实现瀑布流

思路分析: index2.html

flex 实现瀑布流需要将最外层元素设置为 display: flex,即横向排列。然后通过设置 flex-flow:column wrap 使其换行。设置 height: 100vh 填充屏幕的高度,来容纳子元素。每一列的宽度可用 calc 函数来设置,即 width: calc(100%/3 - 20px)。分成等宽的 3 列减掉左右两遍的 margin 距离。

注:横向排列 需要定义 容器高度,这样存在问题,图片过多,会超出容器

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>flex 弹性布局实现瀑布流</title>
    <style>
		body{
			width:920px;
			border: 1px solid #ccc;
			box-sizing: border-box;
		}
        .box {
	          display: flex;  
          flex-flow:column wrap;
          height: 100vh;
        }
        .item {
            margin: 10px;
            width: calc(100%/3 - 20px);
        }
        .item img{
            width: 100%;
            height:100%;
        }
		
    </style>
</head>
<body>
<div class="box">
    <div class="item">
        <img  src="./1.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./2.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./3.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./4.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./5.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./6.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./7.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./8.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./9.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./10.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./11.jpg" alt="" />
    </div>
    <div class="item">
        <img  src="./12.jpg" alt="" />
    </div>
</div>
</body>

19.340 用div 创建一个梯形

<div style=" width: 300px;height: 40px;z-index: 10;position: absolute;left: 50%;transform: translate(-50%);" >
    <div style="" class="map_title_content ">
    	监造项目
    </div>
</div>

<style>
	.map_title_content {
            width: 100%;
            height: 100%;
            justify-content: center;
            display: flex;
            align-items: center;
            position: relative;
            color: white;
            color: #FFFF00;
            font-size: 18px;
        }
        .map_title_content::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            z-index: -1;
            background: #58a;
            transform: perspective(20px) rotateX(-5deg);
            background: -webkit-gradient(linear,0 0,0 bottom, from(rgb(168, 180, 171,0.5)),to(rgb(168, 180, 171,0.8)));
        }
</style>

19.341 标题

效果一: 利用背景图属性渐变色控制画线颜色,通过背景图大小属性设置线条的粗细,文字盒子设置背景覆盖部分线条

image-20210506202132635
image-20210506202132635
<template>
	  <div class="notice">
        <span class="notice_content">
          公告
        </span>
      </div>
</template>
<style>
	.notice {
  position: relative;
  margin: 15px auto 15px;
  width: 100px;
  background-image: linear-gradient(90deg, #fff, #333 50%, #fff);
  background-size: 100% 1px;
  background-position: 50%;
  background-repeat: no-repeat;
  text-align: center;
  
}
.notice_content {
    font-size: 12px;
    color: #333;
    padding: 0 6px;
    background-color: #fff;
  }
</style>

效果二:

image-20210506203731306
image-20210506203731306
<div class="div-line"></div>
<style>
.div-line {
    margin: 0 auto;
    height: 2px;
    width: 100%;
    background: radial-gradient(#1E89A2 12%, white 80%);
}
</style>

效果三:文字光晕

.span1 {
    box-sizing: border-box;
    color: rgb(172, 29, 16);
    max-width: 100%;
    overflow-wrap: break-word;
    text-shadow: 2px 2px 10px rgb(0, 112, 192);
}
.head .title {
    font-size: 3em;
    /* color: #7ddff0; */
    font-weight: 900;
    background-image: -webkit-linear-gradient(top, #04adca, #7ddff0);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-family: Arial, Helvetica, sans-serif;
}

19.342 阴影&渐变色

css3:渐变 linear-gradient和radial-gradientopen in new window

背景模糊

filter: blur(2px);

两侧模糊(圆)

background: radial-gradient(#6fe18c 10%, rgba(0,0,0,0.1) 81%);
background: linear-gradient(#99f, #f99);
#123
.small_bj{
    width: 4.7rem;
    height: 4.7rem;
    background: linear-gradient(0deg, #259AFA 0%, #024EE0 100%);
    border-radius: 50%;
}

阴影&渐变色

box-shadow: 0 0 10px #178236 inset, 0px 0px 30px rgb(0,153,184);

两个参数:0 0 10px #178236 inset, 内阴影

​ 0px 0px 30px rgb(0,153,184); 外阴影

background: linear-gradient(to left, rgb(242, 112, 156), rgb(255, 148, 114));
box-shadow: 0 3px 3px -5px rgb(242, 112, 156), 0 2px 5px rgb(242, 112, 156);

box-shadow: 0 0 10px #178236 inset, 0px 0px 30px rgb(0,153,184);

文字渐变色 https://blog.csdn.net/ayiewu460246/article/details/101789904open in new window

background-image: -webkit-linear-gradient(top, #a80b02, #ff3b30); /*设置颜色与渐变方向*/
background-clip:text;
-webkit-background-clip: text; /*主要用于剪掉文字以外的区域。*/
-webkit-text-fill-color: transparent; /*设置文本的填充颜色。*/
font-family: Arial, Helvetica, sans-serif;
background: linear-gradient(to right, #04adca, #b1c2c2);
    -webkit-background-clip: text;
    color: transparent;
    font-family: Arial, Helvetica, sans-serif;
background: linear-gradient(to right,  #73739e,#dde1e6);
            -webkit-background-clip: text;
            color: transparent;

19.343 html5+css3简单边框发光效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body
        {
            margin: 0;
            padding: 0;

           display: flex;
            justify-content:center;       
            align-items:center;
            min-height:100vh;
            background: #060c21;
            font-family: 'Poppins', sans-serif;
        }
        .box{

            position: relative;
            width: 300px;
            height: 400px;
            display: flex;
            justify-content: center;
            align-items: center;
            background: #060c21;
        }
        /*一个溢出的盒子作为边框,添加背景后形成光源效果*/
        .box::before {
                     content: '';
                     position: absolute;
                     top:-2px;
                     left: -2px;
                     right: -2px;
                     bottom: -2px;
                     background: #FFFFFF;
                     z-index: -1;/*元素堆叠顺序*/
            
        }
        /*另一个溢出的盒子,模糊形成光晕效果*/
        .box::after {
            content: '';
            position: absolute;
            top: -2px;
            left: -2px;
            right: -2px;
            bottom: -2px;
            background: #FFFFFF;
            z-index: -2;
            /*添加模糊滤镜*/
            filter: blur(40px);
        }
        .box::before,
        .box::after{
            /*三色渐变,中间为背景色,融入背景*/
            background: linear-gradient(235deg,#89ff00,#060c21,#00bcd4);
        }
        .content {
            padding: 20px;
            box-sizing: border-box;
            color: #fff;
        }
    </style>
</head>
<body>
<div class="box">
    <div class="content">
        <h1>黑洞</h1>
         <p>
             黑洞是现代广义相对论中,宇宙空间内存在的一种天体。黑洞的引力很大,使得视界内的逃逸速度大于光速。
             “黑洞是时空曲率大到光都无法从其事件视界逃脱的天体”。
             如果将大量物质集中于空间一点,其周围会产生奇异的现象,即在质点周围存在一个界面——“视界”一旦进入这个界面,
             即使光也无法逃脱。这种“不可思议的天体”被美国物理学家约翰·阿奇博尔德·惠勒命名为“黑洞”。
         </p>

    </div>
</div>
</body>
</html>

19.

19.350 弹窗背景

/*白底 作为 图例统计*/
.title_background{
	background-color: rgb(215, 221, 221,0.84);
}
.title_background div:hover {
	background-color:#568080;
}


/*蓝底 一般作为 底部 菜单*/
.main_background {
    background-color: rgb(52, 106, 181, 0.8);
    color: #FFFFFF !important;
    box-shadow: 0px 0px 15px 0px rgba(24, 249, 234, 0.25);
    border-top-right-radius: 8px;
    border-top-left-radius: 8px;
}

/* 透明黑 */
.loginmain {
    background: rgba(0,0,0,.5);
    width: 540px;
    height: 300px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    box-shadow: -15px 15px 15px rgba(6,17,47,.7);
    z-index: 99999;
}

CSS3中的变形处理——transform功能(旋转、缩放、倾斜、移动)

CSS3中的变形处理

参考网址: https://blog.csdn.net/qq_40542728/article/details/81979163open in new window

注:transform:rotate失效 添加属性 display:inline-block;

1 transform属性
在CSS3中,可以利用transform功能实现文字或图像的旋转、缩放、倾斜、移动这4中类型的变形处理。

(1)浏览器支持

到目前为止:Safari3.1以上、Chrome8以上、Firefox4以上、Opera10以上浏览器支持该属性。 

2 旋转
使用rotate方法,在参数中加入角度值,角度值后面跟表示角度单位的“deg”文字即可,旋转方向为顺时针方向。

transform:rotate(45deg);

3 缩放 
使用scale方法来实现文字或图像的缩放处理,在参数中指定缩放倍率。

transform:scale(0.5);//缩小一半

(1)可以分别指定元素的水平方向的放大倍率与垂直方向的放大倍率

transform:scale(0.5,2);//水平方向缩小一半,垂直方向放大一倍。

4 倾斜 
使用skew方法实现文字或图像的倾斜处理,在参数中分别指定水平方向上的倾斜角度与垂直方向上的倾斜角度。

transform:skew(30deg,30deg)//水平方向上倾斜30度,垂直方向上倾斜30度。

(1)只使用一个参数,省略另一个参数

这种情况下视为只在水平方向上进行倾斜,垂直方向上不倾斜。

transform:skew(30deg);

5 移动
使用translate方法来移动文字或图像,在参数中分别指定水平方向上的移动距离与垂直方向上的移动距离。

transform:translate(50px,50px);// 水平方向上移动50px,垂直方向上移动50px

(1)只使用一个参数,省略另一个参数

这种情况下视为只在水平方向上移动,垂直方向上不移动。

transform:translate(50px);

6 对一个元素使用多种变形的方法
transform:translate(150px,200px) rotate(45deg) scale(1.5);

7 指定变形的基准点
在使用transform方法进行文字或图像变形的时候,是以元素的中心点为基准点进行变形的。

transform-origin属性
使用该属性,可以改变变形的基准点。

transform:rotate(45deg);

transform-origin:left bottom;//把基准点修改为元素的左下角

(1)指定属性值

基准点在元素水平方向上的位置:left、center、right

基准点在元素垂直方向上的位置:top、center、bottom

8 3D变形功能
(1)旋转

分别使用rotateX方法、rotateY方法、rotateZ方法使元素围绕X轴、Y轴、Z轴旋转,在参数中加入角度值,角度值后面跟表示角度单位的deg文字即可,旋转方向为顺时针旋转。

transform:rotateX(45deg);

transform:rotateY(45deg);

transform:rotateZ(45deg);

transform:rotateX(45deg) rotateY(45deg) rotateZ(45deg);

transform:scale(0.5) rotateY(45deg) rotateZ(45deg);

(2)缩放

分别使用scaleX方法、scaleY方法、scaleZ方法使元素按X轴、Y轴、Z轴进行缩放,在参数中指定缩放倍率。

transform:scaleX(0.5);

transform:scaleY(1);

transform:scaleZ(2);

transform:scaleX(0.5)scaleY(1);

transform:scale(0.5) rotateY(45deg);

(3)倾斜

分别使用skewX方法、skewY方法使元素在X轴、Y轴上进行顺时针方向倾斜(无skewZ方法),在参数中指定倾斜的角度

transform:skewX(45deg);

transform:skewY(45deg);

(4)移动

分别使用translateX方法、translateY方法、translateZ方法、使元素在X轴、Y轴、Z轴方向上进行移动,在参数中加入移动距离。

transform:translateX(50px);

transform:translateY(50px);

transform:translateZ(50px);

案例

img
img
.popu_window_pointer {
    top: -8px;
    left: -3px;
    position: absolute;
    background: rgba(0,56,114,0.8);
    width: 20px;
    height: 20px;
    transform: skew(30deg,30deg);/* 倾斜  在参数中分别指定水平方向上的倾斜角度与垂直方向上的倾斜角度*/
}

19.360 css引入图片相对路径

image-20201219095123934
image-20201219095123934

19.370 自定义样式 一些案例

自定义标签,按钮

61)标签
<span  id="1" class="labelSpan labelS" style="border-color:#cca4e3">开心 </span>
.labelS {
		    padding: 5px 10px;
		    margin-right: 10px;
		    margin-bottom: 5px;
		    border: 1px solid;
		    border-radius: 5px;
		    float: left;
		    cursor: pointer;
		    background-color: rgba(0, 0, 0, 0);
		}
img
img

19.380 锚点

页面点击事件触发点
<div class="item-nav fl click_light cur" data_type="rmhd">
 
<div class="cont-info-wrap mb80" id="rmhd">
    需要跳转到的页面位置
</div>

<style>
    // 锚点 实现代码段:
    $('.click_light').on('click',function(){
        var type = $(this).attr("data_type");
        window.location.href = '#' + type;
    });
</style>

scrollIntoView 使用

https://www.cnblogs.com/nangezi/p/15708016.htmlopen in new window

https://blog.csdn.net/learn8more/article/details/108047794open in new window

/// tab 切换定位到 指定 内容区域,动画过度,并且 定位到内容区域头部
const tabDom = document.querySelector('#content' + index);
tabDom.scrollIntoView({block: "start", inline: "nearest",behavior:"smooth"})

语法:

1.element.scrollIntoView();
2.element.scrollIntoView(alignToTop); //布尔参数
3.element.scrollIntoView(scrollIntoViewOptions); //对象参数 定义滚动动画,对其方式

使用说明:

  1. 直接调用element.scrollIntoView()
  2. 使用 element.scrollIntoView(alignToTop) alignToTop 是布尔参数
alignToTop[可选],目前之前这个参数得到了良好的支持
true元素的顶部将对齐到可滚动祖先的可见区域的顶部。对应于scrollIntoViewOptions: {block: "start", inline: "nearest"}。这是默认值
false元素的底部将与可滚动祖先的可见区域的底部对齐。对应于scrollIntoViewOptions:
  1. 使用 element.scrollIntoView(scrollIntoViewOptions) scrollIntoViewOptions对象参数
scrollIntoViewOptions[可选],目前这个参数浏览器对它的支持并不好,可以查看下文兼容性详情
behavior[可选]定义过渡动画。"auto","instant"或"smooth"。默认为"auto"。
block[可选] "start","center","end"或"nearest"。默认为"center"
inline[可选] "start","center","end"或"nearest"。默认为"nearest"

19.390 dom 操作

  • prepend:追加

    $("#parent").prepend(html);// 给父节点添加 子节点(追加在最后)

  • prepend

    $("#parent").prepend(html);// 给父节点添加 子节点(追加在最前)

  • prependTo

    $("#sonDom").prepend("#parent");// 讲dom元素 迁移到 parent节点下(作为其第一个子元素)

19.400 div横向排列+滚动条显示

.container{
    width: 100%;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}
.container .item{
    display:inline-block;
    box-sizing: border-box;
    width:33%;
}

19.410 文字左右排列

image-20210406182754376
image-20210406182754376
<div class="detail_li justify" >
    <span class="">导线</span>
    <span class="">#211-#214</span>
</div>
<div class="detail_li justify" >
    <span class="">地线</span>
    <span class="">#211-#214</span>
</div>
<div class="detail_li justify" >
    <span class="">金具</span>
    <span class="">12</span>
</div>


<style>
	.detail_li {
    border: 1px #F5F5F5 solid;
    width: 49%;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 7px;
}
    /*两端对齐*/
			.justify {
	            justify-content: space-between;
			    display: inline-flex;
			    align-items: center;
			}
</style>

19.430 web 设置 浏览器 图标

image-20210507152743369
image-20210507152743369
<head>
	<title>集控中心</title>
    <link rel="shortcut icon" href="${fns:getCfgSettingByCode('platform_ioc').fileValueUrl}" type="image/x-icon" /><!-- 浏览器头部 图标--> 
	<meta name="decorator" content="default"/>
</head>	

19.440 HTML中解决双击会选中文本的问题

在父节点中 添加属性

/* HTML中解决双击会选中文本的问题*/
.html_wrap{
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

19.450 浏览器全屏

  • 注:定时器非常耗性能,所以 页面出现ztree,并且异步加载数据的时候,切换全屏,会出现明显的卡顿
/**
 *
 *  全屏 切换
 * @type {boolean}
 */
var fullScreenFlag = false;// 全屏切换
function switchFullScreen(){
    if(!fullScreenFlag){
        requestFullScreen();// 整个网页
        fullScreenFlag = true;
    }else{
        fullScreenFlag = false;
        exitFull();
    }
    switchFullScreenStyle();// 涉及到样式的修改
};
function requestFullScreen() {
    var element=document.documentElement;
    // 判断各种浏览器,找到正确的方法
    var requestMethod = element.requestFullScreen || //W3C
        element.webkitRequestFullScreen ||    //Chrome等
        element.mozRequestFullScreen || //FireFox
        element.msRequestFullScreen; //IE11
    if (requestMethod) {
        requestMethod.call(element);
    }
    else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }
}
//退出全屏 判断浏览器种类
function exitFull() {
    // 判断各种浏览器,找到正确的方法
    var exitMethod = document.exitFullscreen || //W3C
        document.mozCancelFullScreen ||    //Chrome等
        document.webkitExitFullscreen || //FireFox
        document.webkitExitFullscreen; //IE11
    if (exitMethod) {
        exitMethod.call(document);
    }
    else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }
}
/*监听 f11*/
$(document).on('keydown', function (e){
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if(e && e.keyCode == 122){//捕捉F11键盘动作
        e.preventDefault();  //阻止F11默认动作
        var el = document.documentElement;
        var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;//定义不同浏览器的全屏API      //执行全屏
        if (typeof rfs != "undefined" && rfs) {
            rfs.call(el);
        }else if(typeof window.ActiveXObject != "undefined"){
            var wscript = new ActiveXObject("WScript.Shell");
            if (wscript!=null) {
                wscript.SendKeys("{F11}");
            }
        }
        //监听不同浏览器的全屏事件,并件执行相应的代码
        document.addEventListener("webkitfullscreenchange", function() {//
            if (document.webkitIsFullScreen) {
                //全屏后要执行的代码
                fullScreenFlag = true;
            }else{
                //退出全屏后执行的代码
                fullScreenFlag = false;
            }
            switchFullScreenStyle();
        }, false);

        document.addEventListener("fullscreenchange", function() {
            if (document.fullscreen) {
                //全屏后执行的代码
                fullScreenFlag = true;
            }else{
                //退出全屏后要执行的代码
                fullScreenFlag = false;
            }
            switchFullScreenStyle();
        }, false);

        document.addEventListener("mozfullscreenchange", function() {
            if (document.mozFullScreen) {
                //全屏后要执行的代码
                fullScreenFlag = true;
            }else{
                //退出全屏后要执行的代码
                fullScreenFlag = false;
            }
            switchFullScreenStyle();
        }, false);
        document.addEventListener("msfullscreenchange", function() {
            if (document.msFullscreenElement) {
                //全屏后要执行的代码
                fullScreenFlag = true;
            }else{
                //退出全屏后要执行的代码
                fullScreenFlag = false;
            }
            switchFullScreenStyle();
        }, false)
    }
});


// 全屏 切换 样式修改
var switchFullScreenStyle=function(){
    if(!fullScreenFlag){
        $("#quanping").attr("title","全屏显示");
        $("#quanping").find("img").eq(0).attr("src","/XJB/static/images/jkzx/qp_icon.png");
    }else{
        $("#quanping").attr("title","退出全屏");
        $("#quanping").find("img").eq(0).attr("src","/XJB/static/images/jkzx/colse_qp_icon.png")
    }
}

19.451 监听 键盘,上下左右

document.onkeydown = function(ev){
    var ev = ev || window.event;
    onkeydownCallback("currentHtml",ev);
}
/**
         *  监听键盘的处理方式
         * @param type:类型 ,当前页面还是父页面触发, currentHtml:当前页面、 parentHtml:父页面
         * @param ev:监听键盘返回值
         */
var onkeydownCallback=function(type,ev){
    console.log(ev.keyCode);
    switch(ev.keyCode){
        case 37:
            console.log('左');
            shuffling('prev');
            break;
        case 38:
            console.log('上');
            shuffling('prev');
            break;
        case 39:
            console.log('右');
            shuffling('next');
            break;
        case 40:
            console.log('下');
            shuffling('next');
            break;
        default:
            console.log("请按上下左右键");
            break;
    }
}

19.460 class

if($(this_).hasClass("desc")){

}
$(this_).toggleClass("asc");

19.470 css 常用属性

圆角

border-radius: 6px; (可以使方形变为圆形  ) 
-webkit-border-radius: 35px;   
border-top-right-radius: 8px; border-top-left-radius: 8px;(上面左右2个角)
border-bottom-right-radius:8px;
	
border-radius: 8px;(这个边框都加圆角)

伪类

.timeline:before{
    position: absolute;left: -7px;
    top:35%;
    width: 11px;
    height: 11px;
    border: 1px solid #ccc;
    border-radius: 50%;
    background: #ccc;
    content: "";/* 不加 这个  会导致看不到*/
}

rgba 和rgb

移动端,有时候设置 rgb 加透明度,导致无法识别,可以改用 rgba


input 设置 input placeholder默认样式

input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{
    color:rgba(83, 133, 189, 1);
}

19.500 时间控件& 下拉选 的 小三角图标

style='-webkit-appearance: none;' 这个是取消时间控件的小三角图标

去掉背景色和图标一片空白,如果不好看 可以加上 下划线 border-bottom: 1px solid #000 !important; 或者将背景色改为background-color:#FAFAFA;

.dateInput {  //androd 端去掉背景色
	background-color:transparent;  
	FILTER: alpha(opacity=0); /*androd*/  
	/*appearance:none;*/  /*下拉框去掉右侧图标*/  
	-moz-appearance:none;  -webkit-appearance:none; /*下拉框去掉右侧图标*/ 
}

19.510 浏览器适配

@media

/*@media screen*/
@media (min-width: 1024px){

} /*>=1024的设备*/
@media (min-device-width: 1100px) {

} /*>=1024的设备*/
@media (min-device-width: 1280px) {

}
@media (min-device-width: 1366px) {

}
@media (min-device-width: 1440px) {

}
/*主要针对  电脑 使用 150% 的分辨率下*/
@media screen and (min-device-width: 800px) and (max-device-width: 1440px){}
@media screen and (min-device-width: 1440px) and (max-device-width: 1680px){}
@media (min-devce-width: 1920px){}

table内容溢出设置固定,超过部分用..

 <style type="text/css">
     .mytable {  
			    table-layout: fixed;  /*设置表格宽度不随文字增多而变长*/
			    width: 100%;
         		border:0px;  
			    margin: 0px;  /* 表格偏离大小 */ 
			 }  
      .mytable tr td {  
			    text-overflow: ellipsis;  /* for IE */  
			    -moz-text-overflow: ellipsis; /* for Firefox,mozilla */  
			    overflow: hidden;  
			    white-space: nowrap;  
			   /* border: 1px solid; */  
			   /*  text-align: left   */
			 } 
 </style> 

pre标签

<pre> 标签可定义预格式化的文本。被包围在 <pre> 标签 元素中的文本通常会保留空格和换行符。
而文本也会呈现为等宽字体。提示和注释提示: <pre> 标签的一个常见应用就是用来表示计算机的源代码

登录页面

<template>
  <div class="gradient-bg">
    <div class="glass-container">
      <img :src="brandLogo" class="logo" />
      <div v-if="showDebugForm" class="debug-login">
        <!-- 开发环境保留的表单 -->
      </div>
      <div v-else class="status-message">
        <p>{{ loginStatus }}</p>
        <el-button v-if="isTokenInvalid" @click="contactSupport">联系管理员</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isTokenInvalid: false,
      showDebugForm: process.env.NODE_ENV === 'development'
    };
  },
  computed: {
    loginStatus() {
      return this.isTokenInvalid ? '会话已过期' : '系统已自动登录';
    }
  },
  methods: {
    contactSupport() {
      // 跳转至客服系统
    }
  }
};
</script>

<style scoped>
.gradient-bg {
  background-image: linear-gradient(to bottom right, #FC466B, #3F5EFB);
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.glass-container {
  padding: 40px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  text-align: center;
}

.logo {
  width: 120px;
  margin-bottom: 20px;
}
</style>
image-20250318100524541

禁用登录

<div class="container pr" >
   <view :class="{'glass': noSignIn}"></view> 
</div>

<style lang="scss">
    .glass {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(255, 255, 255, 0.3); /* 半透明背景 */
      backdrop-filter: blur(10px); /* 毛玻璃效果,数值越大越模糊 */
    }
</style>

高度相关

window.innerHeight                 // 可视区域高度
document.documentElement.clientHeight // html 高度
document.body.clientHeight            // body 高度

# 获取某个容器真实高度

document.querySelector('.page-container').offsetHeight


22JavaScript和jQuery相关知识

拓展属性:extData

开发常用到的

<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 引入 jQuery Mobile 样式 -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<!-- 引入 jQuery 库 -->
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- 引入 jQuery Mobile 库 -->
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

从配置文件中取参数

${fns:getConfig("dpSockecService")}

22.2 js监听页面点击事件open in new window

    <!-- 第三种方式-->
    <button id="btn" onclick="threeFn()">点我</button>
    <script type="text/javascript">
        var btn = document.getElementById("btn");

        // 第一种 通过点击事件
        btn.onclick = function(){
            alert("这是第一种点击方式");
        }

        // 第二种 监听点击事件
        btn.addEventListener('click', function(){
            alert("这是第二中点击方式");
        })

        // 第三种 通过方法响应点击事件
        function threeFn(){
            alert("这是第三种点击方式");
        }
    </script>
// 监听页面单击事件
jQuery(document).click(function (event){
    if (event.target.id == "shade"){
        // 业务
    }
});

22.3常用方法

toggleClass class属性切换

$("p").toggleClass("main");

光标悬停,光标移除

<div id="bottomFilter1"  onclick="_mapFilter(1);" onmouseover="showPopupMenu()">光标悬停</div>
<div id="bottomFilter1"  onclick="_mapFilter(1);" onmouseleave="hidePopupMenu()">光标移除</div>

遍历

// 元素遍历
$(selector).each(function(index,element))
// 数组遍历
 $.each(arr,function(i,j){
    console.log(i,j);
})

鼠标

鼠标移除:onmouseleave

获取鼠标:onmouseover="showSearch(event);"

jQuery添加元素的方法

  • before() - 在被选元素之前插入内容
  • after() - 在被选元素之后插入内容
  • prepend() - 在被选元素的开头插入内容
  • append() - 在被选元素的结尾插入内容

字符串转 数字

var s = '234';
/********** 字符串在运算操作中会被当做数字类型来处理 ***************/ 
s *= 1;  
/******* string的两个转换函数,只对string有效 ********/
parseInt(s); // 234
parseFloat(s); //234
/************ 强制类型转换 *********************/
Number(s); // 234

oninput:当用户向 中尝试输入时执行 JavaScript 比 onchange 好用

<input type="text" oninput="myFunction()">

**案例:**根据用户输入的 人员(多人用逗号分割)联动获取人数

function getTicketMembersNum(){
    var ticketMembers=$("#ticketMembers").val();
    if(ticketMembers==null ||  ticketMembers==undefined|| ticketMembers==''){
        $("#ticketMembersNum").val('');
        return;
    }
    ticketMembers=ticketMembers.replace(";",";");
    var ticketMembers=ticketMembers.split(";");
    var length = getArrNum(ticketMembers);
    $("#ticketMembersNum").val(length);
}
// 获取数组长度,针对空字符
function getArrNum(arr){
    var result=[];
    $.each(arr,function(index,item){
        if(item!=''&& item!=undefined){
            result.push(item);
        }
    });
    return result.length;
}

22.10 js 中利用枚举

var typeEmum= {
        "startGc":'${ctx}/ownerScreen/dp/jgStatisticsList',
        "stopGc": "http://192.168.10.228:18999/XJB_AHSBD/a/fiveFDP/xjbDataGet/getTowerWeatherDP",
        "userNum": "http://192.168.10.228:18999/XJB_AHSBD/a/fiveFDP/xjbDataGet/getTowerWeatherDP"
    }
    // 使用
typeEmum[type];

22.20 js获取光标位置

https://blog.csdn.net/mafan121/article/details/78519348open in new window

22.30 输入框绑定事件

$("input").on("focus",function(){
            getFocus();
});

22.190 js 获取浏览器高度

https://www.jb51.net/article/44519.htmopen in new window

  • window.screen.height 和 window.screen.width 屏幕分辨率的高,宽

  • window.innerHeight和window.innerWidth得到窗口的高度和宽度 , 针对iframe,获取到的是当前iframe 对应的 高度,宽度

22.195 js获取元素, 设置元素属性

var html = document.getElementsByTagName('html')[0];
var dl_second_nav=document.getElementsByClassName("dl-second-nav")[0];
var J_NavContent=document.getElementById("J_NavContent");
html.style.height = 2500+'px';
//alert(dl_second_nav.style.height);
dl_second_nav.style.height=2400+'px';
J_NavContent.style.height=2400+'px';

22.201 js文字轮播

1.js 动画,文字横向循环滚动

function f() {
    //根据id获取所对应的div,document意思是去整个html文档中找,getElementById是根据ID
    var tag = document.getElementById('i1')
    //拿到div中的文本,注意innertext方法没有括弧
    var content = tag.innerText
    //获取它这个字符串的第一个文字
    var z =content.charAt(0)
    //获取这个文本除第一个字以外的文本,用substring给它起始位置
    var  l = content.substring(1,content.length)
    //把第一个字符放到最后一位拼接起来
    var new_content = l+z
    //用新生成new_content把div中的文本替换掉
    tag.innerText = new_content
}
//setInterval是个定时器,第一个参数是要执行的内容,第二个参数是执行间隔,单位为毫秒
setInterval('f()',300);

动画,逐字添加 单词

<!DOCTYPE html>
<html style="font-size:14px">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" id="view1" content="width=device-width, initial-scale=1, maximum-scale=3.0, user-scalable=yes" />
    <title>网页缩放</title>
	<script>
		var text = "Hello how are you?";
		function typeText() {
			var i = 0;
			var interval = setInterval(function () {
				var parag = document.getElementById("theParagraph");
				parag.innerText = text.substr(0, i);
				if (text.length == i)
					clearInterval(interval);
				i++;
			}, 200)
		}
</script>
</head>
<body>
    <p id="theParagraph"></p>
    <button id="typeButton" onclick="typeText()" style="padding:5px">单击</button>
</body>
</html>

2.JS实现文字向上无缝滚动轮播open in new window

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{margin: 0;padding: 0}
        #box{height: 140px; border: solid 1px; overflow: hidden;}
    </style>
</head>

<body>
    <div id="box">
        <ul id="ul1">
            <li>1111111111111111111111</li>
            <li>2222222222222222222222</li>
            <li>3333333333333333333333</li>
            <li>4444444444444444444444</li>
            <li>5555555555555555555555</li>
            <li>6666666666666666666666</li>
            <li>7777777777777777777777</li>
            <li>8888888888888888888888</li>
            <li>9999999999999999999999</li>
        </ul>
        <ul id="ul2"></ul>
    </div>
    <script>
        window.onload = roll(50);

        function roll(t) {
            var ul1 = document.getElementById("ul1");
            var ul2 = document.getElementById("ul2");
            var box = document.getElementById("box");
            ul2.innerHTML = ul1.innerHTML;
            box.scrollTop = 0;
            var timer = setInterval(rollStart, t);
            box.onmouseover = function () {
                clearInterval(timer)
            }
            box.onmouseout = function () {
                timer = setInterval(rollStart, t);
            }
        }

        function rollStart() {
            if (box.scrollTop >= ul1.scrollHeight) {
                box.scrollTop = 0;
            } else {
                box.scrollTop++;
            }
        }
    </script>
</body>

</html>

22.210 js定时器

var guiJiPolyColortimer = setInterval(function () {
            console.log("定时器");
        }, 600);


 if (guiJiPolyColortimer != null) {
            clearInterval(guiJiPolyColortimer);
        }       

小结:textContent、innerText、innerHTML的区别和差异

目前遇到的场景:

2020-09-10 14:06:34
有个时间格式的字符串如果用 document.getElementById('i1').innerText 会剔除 时间中的空格

1 、textContent属性可以获取指定节点的文本及其后代节点中文本内容,也包括<script><style>元素中的内容;

innerText也是获取指定节点的文本及其后代节点中文本内容,但不能获取<script><style>元素中的内容。

innerHTML是获取HTML文本结构内容。

2、textContent会获取display:none的节点的文本;而innerText好像会感知到节点是否呈现一样,不作返回。

也就是说,textContent能够获取元素的所有子节点上的文本,不管这个节点是否呈现;而innerText只返回呈现到页面上的文本。

3、要注意设置文本时被替换的可不只是文本了;这时textContent 、innerText属性相当于innerHTML属性,会把指定节点下的所有子节点也一并替换掉。

4、由于 innerText 受 CSS 样式的影响,它会触发重排(reflow),但 textContent 不会。

22.220 延迟,定时器

setTimeout(function () {// 延迟
    var num=Math.floor(Math.random()*10+1);
    console.log(num)
},600);


var refUserIdsCheckFlag=false;//作为入住人员 下拉选数据是否获取到到的标识,,因为初始化时需要对其进行默认选中操作
var mSiFunc6=setInterval(function(){// 定时器
    if(refUserIdsCheckFlag){//人员下拉选数据全部获取到后 在执行默认选择功能
        $scope.refUserIdsCheck();//初始化时 对 入住人员复选框 默认选中
        clearInterval(mSiFunc6);
    }
},100);

案例 定时查询数据库


22.221 随机数/uuid

  • 随机数
Math.floor(Math.random() * (max- min) + min);// 不含max  

var num=Math.floor(Math.random()*10+1);// 1-10

//奇偶判断
if(num%2 ==0){
    // 偶数
}else{
    // 奇数
}    


  • uuid
//1.用于生成uuid
function S4() {
	return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function guid() {
	return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
// 调用
var uuid = "cms"+guid();

//2. 利用时间
var uuid = "cms"+mydate.getDay()+mydate.getHours()+mydate.getMinutes()+mydate.getSeconds()+mydate.getMilliseconds()+Math.round(Math.random()*10000);

22.230 获取图片的实际 大小

// 图片地址
var img_url = '13643608813441.jpg'
// 创建对象
var img = new Image()
// 改变图片的src
img.src = img_url
// 判断是否有缓存
if(img.complete){
    // 打印
    alert('from:complete : width:'+img.width+',height:'+img.height)
}else{
    // 加载完成执行
    img.onload = function(){
        // 打印
        alert('width:'+img.width+',height:'+img.height)
    }
}

22.240图片放大的简单例子

场景1

<!DOCTYPE html>
<html lang="zh-cmn-Hans">
  <head>
    <meta http-equiv="Content-Language" content="zh-cn" />
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>用鼠标滚轮滚动控制图片的缩小放大</title>
    <script language="javascript">
      function bbimg(o) {
        console.log(event.wheelDelta);
        var zoom = parseInt(o.style.zoom, 10) || 100;
        zoom += event.wheelDelta / 12;
        if (zoom > 0) o.style.zoom = zoom + "%";
        return false;
      }
    </script>
  </head>
  <body>
    <p>将鼠标放在图片上,点击一下,然后滚动鼠标滚轮试试看</p>
    <p>
      <img border="0" src="https://lishihuan.oss-cn-shanghai.aliyuncs.com/img/20200914161940.jpg" onmousewheel="return bbimg(this)" />
    </p>
  </body>
</html>

场景2:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>移动缩放图片</title>
  </head>
  <body>
    <style>
      #log {
        position: fixed;
        top: 0;
        right: 0;
        width: 200px;
        background: #eee;
        color: #333;
        padding: 5px;
      }
    </style>
    <div id="log"></div>
    <script>
      function log() {
        document.getElementById("log").innerHTML =
          document.getElementById("log").innerHTML +
          "<br>" +
          [].join.call(arguments, ",");
      }
    </script>

    <style>
      * {
        margin: 0;
        padding: 0;
      }
      body {
        background: #333;
      }
      #box {
        position: relative;
        overflow: hidden;
        margin: 50px auto;
        border: 1px solid #fff;
        background: #fff;
      }
      #box img {
        position: absolute;
      }
    </style>
      <!-- 需要注意,如果没有实现效果,可能是 box,img标签需要把width,height属性写入到 元素上,不能写在css文件中-->
    <div id="box" style="width: 500px; height: 500px;">
      <img src="http://cdn.iknow.bdimg.com/static/common/pkg/common_z_63fa369.png" style="width: 827px; height: 262px;"/>
    </div>

    <script>
      evnt = function (event) {
            var evn = event,
            eventDoc, doc, body,
            button = evn.button
            evn.target = evn.target || evn.srcElement;

        // Calculate pageX/Y if missing and clientX/Y available
        if (evn.pageX == null && evn.clientX != null) {
            eventDoc = evn.target.ownerDocument || document;
            doc = eventDoc.documentElement;
            body = eventDoc.body;

            evn.pageX = evn.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
            evn.pageY = evn.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
        }

        if (!evn.preventDefault) {
            evn.preventDefault = function() {
                this.returnValue = false;
            }
        }

        if (!evn.stopPropagation) {
            evn.stopPropagation = function() {
                this.cancelBubble = true;
            }
        }

        if (evn.which == null && (evn.charCode != null || evn.keyCode != null)) {
            evn.which = evn.charCode != null ? evn.charCode : evn.keyCode;
        }

        // Add which for click: 1 === left; 2 === middle; 3 === right
        // Note: button is not normalized, so don't use it
        if (!evn.which && button !== undefined) {
            evn.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
        }
        return evn
    };

    function getOffset(o) {
        var left = 0,
            top = 0;
        while (o != null && o != document.body) {
            top += o.offsetTop;
            left += o.offsetLeft;
            o = o.offsetParent;
        }
        return {
            left: left,
            top: top
        };
    }

      (function() {
            var d = document,
                bind = function(b, a, c) {
                    b.addEventListener ? b.addEventListener(a, function(event) {
                        c.call(b, evnt(event));
                    }, false) : b.attachEvent("on" + a, function(event) {
                        c.call(b, evnt(window.event));
                    });
                },
                on = function(b, o) {
                    for (var a in o) {
                        bind(b, a, o[a]);
                    }
                };

            var isRun,
                startX,
                startY,
                endX,
                endY,
                rX,
                rY,
                bgX = 0,
                bgY = 0,
                $b = d.getElementById("box");
            ww = parseInt($b.style.width),
            wh = parseInt($b.style.height),
            i = $b.getElementsByTagName('img')[0],
            img = i.style,
            imgw = parseInt(img.width),
            imgh = parseInt(img.height),
            scaleSize = 1;

            function rs() {
                var w, h;
                //以完全显示图片为基准,如果改为>,则为以铺满屏幕为基准
                if (ww / wh < imgw / imgh) {
                    w = ww;
                    h = imgh * ww / imgw;
                    bgX = 0;
                    bgY = -(h - wh) / 2;
                    scaleSize = ww / imgw; //初始比率
                } else {
                    w = imgw * wh / imgh;
                    h = wh;
                    bgX = -(w - ww) / 2;
                    bgY = 0;
                    scaleSize = wh / imgh;
                }
                img.width = w + "px";
                img.height = h + "px";
                img.left = bgX + "px";
                img.top = bgY + "px";
            }
            rs();
            /* Init */
            on(d, {
                "mousedown": function(e) {

                    //按中建快速还原大小
                    if (e.which === 2) {
                        rs();
                    }
                    if (e.which === 1 && e.target && (e.target === i || e.target === $b)) {
                        isRun = true;
                        startX = e.pageX;
                        startY = e.pageY;

                        e.preventDefault();
                    }
                },
                "mouseup": function(e) {
                    if (e.which !== 1) {
                        return;
                    }

                    img.cursor = "default";
                    isRun = false;
                     if(typeof(rX)!=="undefined")//这个判断原作没有,去掉该判断会出现单击后,放大缩小不是鼠标位置的情况;处理加载后就点击的情况;即rX是undefined          
                    {
                        bgX = rX;
                        bgY = rY;
                    }

                    e.preventDefault();
                },
                "mousemove": function(e) {
                    //
                    if (e.which !== 1) {
                        return;
                    }
                    if (isRun) {
                        e.preventDefault();
                        img.cursor = "move";
                        endX = e.pageX;
                        endY = e.pageY;
                        rX = bgX + endX - startX;
                        rY = bgY + endY - startY;

                        img.left = rX + "px";
                        img.top = rY + "px";
                    }
                },
                "mousewheel": function(e) {
                    //以鼠标为中心缩放,同时进行位置调整
                    var deltaY = 0;
                    var x = e.pageX;
                    var y = e.pageY;

                    e.preventDefault();

                    if (e.target && (e.target === i)) {

                        var l = getOffset($b);
                        x = x - l.left;
                        y = y - l.top;

                        var p = (e.wheelDelta) / 1200;
                        var ns = scaleSize;
                        ns += p;
                        ns = ns < 0.1 ? 0.1 : (ns > 5 ? 5 : ns); //可以缩小到0.1,放大到5倍

                        //计算位置,以鼠标所在位置为中心
                        //以每个点的x、y位置,计算其相对于图片的位置,再计算其相对放大后的图片的位置
                        bgX = bgX - (x - bgX) * (ns - scaleSize) / (scaleSize);
                        bgY = bgY - (y - bgY) * (ns - scaleSize) / (scaleSize);
                        scaleSize = ns; //更新倍率

                        img.width = imgw * ns + "px";
                        img.height = imgh * ns + "px";
                        img.top = bgY + "px";
                        img.left = bgX + "px";
                    }
                }
            });

        })();
    </script>
  </body>
</html>

22.250 语音播报

<script type="text/javascript">
    // 语音播报
    var audio;
    voiceadiomethod=function(text) {
        if(!voiceRecognitionFlag){
            //layui.layer.msg("语音播报已关闭.......");
            return;
        }
        if (text && text != '') {

            if (audio) {
                try {
                    document.body.removeChild(audio);// 移除 音频控件
                } catch (e) {
                    console.log("无需移除:"+e)
                }
            }
            text = encodeURIComponent(text);
            var address = "https://tts.baidu.com/text2audio?lan=zh&pdt=301&vol=9&per=0&cuid=baike&ctp=1&tex=" + text;
            // 如果浏览器支持,可以设置autoplay,但是不能兼容所有浏览器
            audio = document.createElement('audio');
            audio.id = "aaron";
            audio.autoplay = true;
            audio.preload = true;
            audio.controls = true;
            audio.src = address;
            audio.addEventListener('ended', function () {
                // 设置则播放完后移除audio的dom对象
                document.body.removeChild(audio);
            }, false);
            audio.addEventListener('error', function () {
                document.body.removeChild(audio);
                console.log('合成出错url:' + address + '\nAudio错误码:' + audio.error.code);
            }, false);
            audio.loop = false;
            audio.volume = 1;
            // 在body元素下apppend音频控件
            document.body.append(audio);
        }
    }
    // 移除语音播报
    removeAudio=function(){
        if (audio) {
            try {
                document.body.removeChild(audio);// 移除 音频控件
            } catch (e) {
                console.log("无需移除:"+e)
            }
        }
    }
</script>

22.160 iframe

https://www.cnblogs.com/kongbursi-2292702937/p/12113101.htmlopen in new window

  • scrolling="no" 禁用滚动条
  • 父页面调用子页面的 方法 window.frames["ifrom_name"].methodsChild();
  • 取iframe 页面高度,定义样式
<script>
    //父页面调用子页面的 方法
    function findMore() {
        // 调用子页面 findMore 方法
        window.frames["window_popup_iframe"].findMore();
        // 如果上面的方法报错,则用下面这个
         document.getElementById("taskContent").contentWindow.findMore();// 调用子页面方法
        document.getElementById("taskContent").contentWindow.document.getElementById('dundianId').value=id;// 给子页面赋值
       
        
        
    }
    // 取iframe 页面高度,定义样式
    function changeIframeStyle(){
        var Scale = document.querySelector("iframe").offsetParent;// 正常应该是下面的写法,但是目前还不知道,为什么有时不行
    	var Scale = document.querySelector("iframe").contentDocument.querySelector("body");
    	Scale.style.transform = "scale("+ zoomScale +",1)";
    }  
    // ifame 给父页面赋值
    parent.document.getElementById('f_id').value = 'xxxxxxx';
    

    
</script>

<iframe id="window_popup_iframe" name="window_popup_iframe"  width="1780" height="1216" frameborder="no" scrolling="no" border="0"
	src="/CPMS/a/ownerScreen/dp/jgStatisticsList?type=startGc"  marginwidth="0" marginheight="0" allowtransparency="yes" 
	style="overflow: auto !important;" >
</iframe>



js和jquery给iframe src赋值的3种方法open in new window

  • 方法一

这是最常用的js给iframe src赋值的方法,代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>iframe src赋值的方法</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<iframe frameborder="1" id="barframe" ></iframe>
</body>
</html>
<script type="text/javascript">
document.getElementById("barframe").src = "http://localhost/EXAMPLE/iframe/example.html";
</script>
  • 方法二

通过js创建一个iframe元素,然后再给该元素src赋值,代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>iframe src赋值的方法</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
</body>
</html>
<script type="text/javascript">
var myIframe = document.createElement('iframe');
myIframe.src = 'http://localhost/EXAMPLE/iframe/example.html';
document.body.appendChild(myIframe);

/**
	 var myIframe = document.createElement('iframe');
        myIframe.src = '${ctx}/map3D/map3DPopup?pmisid=12M00000035386353';
        myIframe.id = 'towerPopFrame';
        myIframe.width = $("#tower_pop_wrap").width();
        myIframe.height = $("#tower_pop_wrap").height();
        document.getElementById("tower_pop_wrap").appendChild(myIframe);

*/

</script>

最后一句 document.body.appendChild(myIframe); 是表示在 body 里添加刚定义的 myIframe 这个控件。

我们也可以把该iframe添加到某一个div容器里,写法如下:document.getElementById("div1").appendChild(myIframe); , div1是该div容器的id 。

  • 方法三

上面两个方法都是用js来实现的,其实我们也可以用jquery来实现,代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>iframe src赋值的方法</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://www.webkaka.com/script/jquery-1.4.2.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
  $('#barframe').attr('src', 'http://localhost/EXAMPLE/iframe/example.html');
});
</script>
</head>
<body>
<iframe frameborder="1" id="barframe"></iframe>
</body>
</html>

特别注意,上述jquery代码不能缺少 $(document).ready(); ,否则iframe src赋值失败,除非把jquery的代码放在 <iframe ... 的html代码后面。此外,还需要在 <head></head> 里引用 jquery.js 文件

案例:

<div id="tower_pop" class="tower_pop hide" style="width: 40%;height: 100%;overflow: hidden;top: 0px;right: 0px;position: absolute;" >
        <div id="tower_pop_wrap" style="width:100%;height: 100%;border: 1px #f10707 solid;"></div>
</div>
<script type="text/javascript">
   showTowerPopup=function(){
    if($("#tower_pop").hasClass("hide")){// 显示
        $("#tower_pop").removeClass("hide");
        var myIframe = document.createElement('iframe');
        myIframe.src = '${ctx}/map3D/map3DPopup?pmisid=12M00000035386353';
        myIframe.id = 'towerPopFrame';
        myIframe.width = $("#tower_pop_wrap").width();
        myIframe.height = $("#tower_pop_wrap").height();
         myIframe.scrolling = 'no';
            myIframe.frameborder = 'no';
        document.getElementById("tower_pop_wrap").appendChild(myIframe);
    }else{//隐藏
        $("#tower_pop").addClass("hide");
        $("#tower_pop_wrap").empty();
    }
} 
</script>

iframe 设置高度

可以不用通过jq 来自定义高度,直接通过 width="100%" height="100%" 来保证高度100%

                <iframe id="mainFrame" name="mainFrame" src="${ctx}/jkzx/jkzxModule/mainContent" style="" scrolling="yes" frameborder="no" width="100%" height="100%"></iframe>htmL

iframe 父页页面

  • 父页面获取iframe页面

    • 父页面获取iframe页面元素

      • JavaScript:window.frames["iframeId"].document.getElementById("元素id")

      document.getElementById("iframeId").contentWindow.document.getElementById("元素id")

      • jquery: $("#元素id", document.frames("iframeId").document) 如果报错 就用下面这个

      $('#iframeId').contents().find("#元素id")[0]

    • 父页面获取iframe页面的方法

      • var ifra = document.getElementById("ifra");
        ifra.contentWindow.funcName();
        
      • $("#indexL")[0].contentWindow.funcName();

  • iframe获取父页面

    • 获取 父页面的 元素
      • JavaScript: $(window.parent.document.getElementById("元素id"))
      • jquery: $("#元素id", parent.document)
    • 获取父页面函数: 先通过window.parent获取到父元素,在调用该对象上的方法
      • JavaScript: window.parent.funcName()
      • jquery: $(window.parent)[0].funcName()
  • 父页面获取iframe页面函数方法: 先获取到子页面的window对象,然后在调用

window.onload = function() {
  var ifra = document.getElementById("ifra");
  ifra.contentWindow.funcName();
}

监听iframe 页面加载完成事件

$(document).ready(function() {
            var iframe = document.getElementById("mainFrame");
            if (iframe.attachEvent) {
                iframe.attachEvent("onload", function() {
                    //iframe加载完成后你需要进行的操作
                    alert("加载完成")
                });
            } else {
                iframe.onload = function () {
                    //iframe加载完成后你需要进行的操作
                    alert("加载完成2222")
                };
            }
        })
;

案例:tab切换,iframe修改 src

<style>
	.header{
            font-family: Microsoft YaHei;
            font-size: 1.3em;
            font-weight: 800;
            height: 40px;
            width: 100%;
            display: flex;
            align-items:center;
            justify-content:center;
            padding: 10px 0;
        }
        .header_wrap{
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 25px;
            background: #012445;
            border: 1px solid #104c8b;
        }
        .header .tab{
            color: #6f7886;
            cursor: pointer;
            padding: 8px 30px;
            border-radius: 25px;
            animation-delay:1s;
            -webkit-animation-delay:2s; /* Safari 和 Chrome */
        }
        .header .tab.check{
            color: #333;
            background: #eee;
            box-shadow: 0px 1px 2px rgba(0,0,0,0.2);
            /*background: linear-gradient(to bottom, #eeeff9 0%,#3399ff 100%);*/
        }
</style>

<%-- 头部--%>
    <div class="header">
        <div class="header_wrap">
            <div id="pic_detail" class="tab check" style="" onclick="switchTab(this,'pic_detail');">图像</div>
            <div id="list_detail" class="tab" onclick="switchTab(this,'list_detail');" >详情</div>
        </div>
    </div>
 var urlType={
            'pic_detail':'${ctx}/trans/trans/transPictureOnlyNew?isCj=${isCj}&equipid=${equipid}&rtime=${rtime}&jkzx=${jkzx}',
            'list_detail':'${ctx}/trans/trans/transPictureDetail?isCj=${isCj}&equipid=${equipid}&rtime=${rtime}&jkzx=${jkzx}',
        }
        var tabType = 'pic_detail';// 默认查询图片
        // tab 切换
        function switchTab(this_,id){
            tabType = id;
            $(".tab").removeClass("check");
            $(this_).addClass("check");
            loading("数据加载中,请稍等.....");
            $("#mainFrame").attr("src",urlType[tabType]);
        }

案例 大屏固定尺寸 需要嵌入一个 其他大屏,也是固定尺寸的,

项目说明:

应急大屏 width: 2880px; height: 1200px; 物资 width: 1920px; height: 1080px;

应急大屏首页,需要点击跳转到 物资和无人机大屏 ,但是物资大屏的尺寸不一致,开发思路是,点击 物资大屏时,创建一个全屏的div,嵌入一个iframe页面,尺寸100%

然后 在这个iframe里面对 物资大屏进行 缩放,从而到达完全契合

xiaoguotu
xiaoguotu
  • 父页面
<style>
.hide {
  display: none !important;
}
</style>
<script>
	// 点击跳转到 其他大屏 以 div 弹窗层的形式 嵌入对应的页面
    var layerLoadIndex;
    showTowerPopup = function (url) {
        if ($("#box_count_wrap").hasClass("hide")) {// 显示
            $("#box_count_wrap").removeClass("hide");
            var myIframe = document.createElement('iframe');
            myIframe.src = url;
            myIframe.id = 'popupIframe';
            myIframe.width = $("#box_count").width();
            myIframe.height = $("#box_count").height();
            myIframe.scrolling = 'no';
            myIframe.frameborder = 'no';
            document.getElementById("box_count").appendChild(myIframe);
            popupIframeListening('popupIframe');
            // load
            layerLoadIndex = layer.load(0, {shade: false}); //0代表加载的风格,支持0-2
        } else {//隐藏
            $("#box_count_wrap").addClass("hide");
            $("#popupIframe").remove();
            $("#box_count").html();
            layer.close(layerLoadIndex);
        }
    }
    // 弹窗 iframe 监听
    var popupIframeListening=  function(popupIframe){
        var iframe = document.getElementById(popupIframe);
        if (iframe.attachEvent) {
            iframe.attachEvent("onload", function() {
                //iframe加载完成后你需要进行的操作
                console.log("iframe:"+popupIframe +"初始化完成");
                layer.close(layerLoadIndex);
            });
        } else {
            iframe.onload = function () {
                //iframe加载完成后你需要进行的操作
                console.log("iframe:"+popupIframe +"初始化完成");
                layer.close(layerLoadIndex);
            };
        }
    }
</script>
<div id="box_count_wrap" style="width:100%;height: 100%;z-index: 30;position: absolute;left: 0px;top: 0px;"
     class="hide">
    <div id="box_count" style="width:100%;height: 100%"></div>
    <div id="box_count_button" style="position: absolute;right: 50px;top: 50px;height: 30px;width: 30px;"
         onclick="showTowerPopup('');">
        <img width="30px;" src="${ctxStatic}/juanzhou/back.png" alt="关闭">
    </div>
</div>
  • 物资大屏中间页面(原页面 无法控制,所以中间 加一层 页面,用来控制尺寸)

有当前页对 物资大屏和 应急大屏尺寸计算 ,从而 通过 transform: scale 达到2个不同尺寸的页面的完全契合

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/include/taglib.jsp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>物资大屏</title>
    <style type="text/css">

        html,body,#wzContent{
            width: 100%;height: 100%;
            padding: 0;
            margin: 0;
        }

    </style>
    <script src="${ctxStatic}/jquery/jquery-1.8.3.min.js" type="text/javascript"></script>
    <script>
        /*
        * 页面加载完成后,添加 物资 大屏
        *   物资大屏尺寸1920*1080 需要对其缩放
        *   通过 transform: scale(x,y);
        * */
        window.onload = function() {

            // var myIframe = document.createElement('iframe');
            // myIframe.src = 'http://172.16.10.242:9090/SDT_IMOA/a/material/materialIndex/dpView';
            // myIframe.id = 'wzIframe';
            // myIframe.width = 1920;
            // myIframe.height =1080;
            // myIframe.scrolling = 'no';
            // myIframe.frameborder = 'no';
            // myIframe.transform='scale(1.5,1.1111)';
            // document.getElementById("wzContent").appendChild(myIframe);

            var popupIframe = $(window.parent.document.getElementById("popupIframe"));
            var window_width = popupIframe.width();
            var window_height = popupIframe.height();
            // 子iframe 尺寸
            var wzContent_size={
                x:1920,
                y:1080,
            }
            var scaleX=window_width/wzContent_size.x;
            var scaleY=window_height/wzContent_size.y;
            var url = 'http://172.16.10.242:9090/SDT_IMOA/a/material/materialIndex/dpView';// 物资大屏 
            var html=`
                    <div id="wz_wrap" class="wz_wrap" style="width: 100%;height:0;" >
                        <iframe id="wzIframe" name="wzIframe" src="\${url}" width="\${wzContent_size.x}" height=\${wzContent_size.y}"
                            frameborder="no" border="0" marginwidth="0"  marginheight="0" scrolling="no" allowtransparency="yes"
                            style="overflow: hidden !important;transform: scale(\${scaleX},\${scaleY});transform-origin:left top;" >
                        </iframe>
                    </div>
                `;
            $("#wzContent").prepend(html);// append
            $("#wz_wrap").animate({
                height:window_height+'px',
                opacity:1
            });
        }
    </script>
</head>
<body style="overflow: auto;margin: 0px;background-color: rgba(2,25,101,0.9);">
<%-- 物资大屏--%>
    <div id='wzContent' style="">
        <%--<iframe id="wzIframe" name="wzIframe" src="http://172.16.10.242:9090/SDT_IMOA/a/material/materialIndex/dpView" width="1920" height="1080"
                frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="yes"
                style="overflow: hidden !important;transform: scale(1.5,1.1111);transform-origin:left top;">
        </iframe>--%>
    </div>
</body>
</html>

iframe 跨域问题 -通过nginx 来实现

需要实现播放视频音频的iframe

<iframe allow="camera; microphone; fullscreen; display-capture; autoplay"
                src="https://192.168.2.9:3030/voice/1" style="border: 0px;position: absolute;top: 100px;left: 0;"></iframe>

22.170 js 获取服务器域名、ip、端口

var pathName=window.document.location.pathname;
    var curWwwPath=window.document.location.href;
    var pos=curWwwPath.indexOf(pathName);
    var prefixUrl=curWwwPath.substring(0,pos);
    console.log("pathName:"+pathName);
    console.log("curWwwPath:"+curWwwPath);
    console.log("pos:"+pos);
    console.log("prefixUrl:"+prefixUrl);
    
    alert("location:"+window.location);//location:http://localhost:8080/CPMS/a/mapMake/mapMakeIndex
        alert("href: "+window.location.href);//href: http://localhost:8080/CPMS/a/mapMake/mapMakeIndex
        alert("protocol: "+window.location.protocol);//http:
        alert("host&port: "+window.location.host);//localhost:8080
        alert("port: "+window.location.port);//8080
        alert("hostname: "+window.location.hostname);//localhost
    
    
    
    
    

22.170 回车

<input id="search-input" type="text" class="search-input" placeholder="请输入关键字" style="font-size: 25px;"
                       autocomplete="off" onkeydown="keyDownSeach(event);"><%--onchange="inputSearch(this, event);"--%>
<button id="searchButton" class="search-icon" onclick="inputSearch(this, event);"><span></span></button>
<script>
    //回车触发搜素,搜素
    function keyDownSeach(e) {
        // 兼容FF和IE和Opera
        var theEvent = e || window.e;
        var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
        if (code == 13) {
            $("#searchButton").click();
        }

    }
    
        // 搜索
    function inputSearch(evt) {
        //var inputSearch = $(obj).val().trim();
        var inputSearch = $("#search-input").val().trim();
        if (inputSearch == null || inputSearch == '' || inputSearch == undefined) {
            return;
        }
        $("#resultHtml").empty();// 清空,
        $('#resultHtml').fadeIn();//菜单栏 淡入
        resultHtmlForInputSearch(inputSearch,false);// 将方法迁移出来, 方便语音识别用到
    }
</script>           
                
                

22.180 移动鼠标拖动窗口

https://my.oschina.net/u/4383702/blog/3678751open in new window

拖动窗口.html

使用 jquery-ui.min.js 的 draggable 方法

<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<script src='http://libs.baidu.com/jquery/1.7.2/jquery.min.js'></script>
		<script src="http://libs.baidu.com/jqueryui/1.9.0/jquery-ui.min.js "></script>
		<style>
			#draggable { width: 150px; height: 150px; padding: 0.5em; border:#AAA
			1px solid; background-color:#EEE; }
		</style>
	</head>
	<body>
		<div id="draggable"> 求拖走 </div>
		<script>
			$(function() {   
				$("#draggable").draggable({
					draggable: false
				});
			});
		</script>
	</body>

</html>

22.190 元素title 属性

<style>
	  #mytitle {
            position: absolute;
            color: black;
            max-width: 460px;
            font-size: 14px;
            line-height:29px;
            padding: 4px;
            background: white;
            border: solid 1px #e9f7f6;
            border-radius: 5px;
        }
</style>
<script>
 $(function () {
            var x = 10;
            var y = 20;
            var newtitle = '';
            $('.tityou').mouseover(function (e) {
                newtitle = this.title;
                this.title = '';
                if(newtitle!=""){
                    $('body').append('<div id="mytitle" >' + newtitle + '</div>');
                }
                $('#mytitle').css({
                    'left': (e.pageX + x + 'px'),
                    'top': (e.pageY + y - 80 + 'px')
                }).show();
            })
            .mouseout(function () {
                this.title = newtitle;
                $('#mytitle').remove();
            }) 
            
            .mousemove(function (e) {
                $('#mytitle').css({
                   'left': (e.pageX + x +10 + 'px'),
                    'top': (e.pageY + y - 60 + 'px'),
                    'font-size':29+'px'
                }).show();
            })
        });

</script>

22.200 d3 的使用---待整理

https://blog.csdn.net/mylovewanzi/article/details/99703445open in new window 利用 d3 自定义比例尺


22.210 My97DatePickeropen in new window 组件

https://blog.csdn.net/xiangff_csdn/article/details/78688506open in new window

<!--开始时间 -->
<input name="applyStart" id="applyStart" type="text"  class="input-medium Wdate required"
                           value="<fmt:formatDate value="${ydxjApply.applyStart}" pattern="yyyy-MM-dd"/>"
                           onclick="WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:true,maxDate:'#F{$dp.$D(\'applyEnd\')}',isShowClear:true,onpicked:pickedFunc});" />
<!--结束时间 -->
<input name="applyEnd" id="applyEnd" type="text"  class="input-medium Wdate required"
                           value="<fmt:formatDate value="${ydxjApply.applyEnd}" pattern="yyyy-MM-dd"/>"
                           onclick="WdatePicker({minDate:'#F{$dp.$D(\'applyStart\')}',dateFmt:'yyyy-MM-dd',isShowClear:true,onpicked:pickedFunc});"/>

<script type="text/javascript">
    /**
		自定义单击事件:
         	onpicked:pickedFunc
    		onpicked:function(){getRuleName();
    */
    
	 /*计算天数*/
        function datedifference(sDate1, sDate2) {//sDate1和sDate2是2006-12-18格式
            var dateSpan, tempDate, iDays;
            sDate1 = Date.parse(sDate1);
            sDate2 = Date.parse(sDate2);
            dateSpan = sDate2 - sDate1;
            dateSpan = Math.abs(dateSpan);
            iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
            return iDays+1;
        }
        /* 计算 请假天数*/
        function pickedFunc() {
            var applyStart = $("#applyStart").val();
            var applyEnd = $("#applyEnd").val();
            if(applyStart!=null && applyStart!=''&& applyEnd!=null && applyEnd!=''){
                $("#applyDays").val(datedifference(applyEnd,applyStart));
            }
        }
</script>

a) 在发list页面 只展示用:<fmt:formatDate value="${planWorkTicket.timeFlow}" pattern="yyyy-MM-dd HH:mm:ss"/>

b) 在form页面 <input name="planStartDate" type="text" maxlength="20"

value="<fmt:formatDate value="${planWorkTicket.planStartDate}" pattern="yyyy-MM-dd HH:mm:ss"/>" onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:true});"/>

img
img
<!--list 页面时间段查询  -->
<form:input path="createDateStart" autocomplete="off" onclick="WdatePicker({dateFmt:'yyyy-MM-dd'});"  class="input-medium Wdate"/><form:input path="createDateEnd" autocomplete="off" onclick="WdatePicker({dateFmt:'yyyy-MM-dd'});"  class="input-medium Wdate"/>

<!--
    <if test="createDateStart != null and createDateStart != ''">
        AND to_char(a.create_date,'yyyy-MM-dd') <![CDATA[ >= ]]> #{createDateStart}
    </if>
    <if test="createDateEnd != null and createDateEnd != ''">
        AND to_char(a.create_date,'yyyy-MM-dd') <![CDATA[ <= ]]> #{createDateEnd}
    </if>
-->


  • 利用字符串拼接使用时间组件
var html='<tr class="tbTrJd tbTrJdTj" id="trJdTj'+index+'">'+
		'<td style="border:1px grey solid;text-align: center;"><input name="planWorkTicketGroundwireList['+num+'].startTime" id="startTime'+num+'" type="text" class="readOnlyInput"   							onclick="WdatePicker({dateFmt:\'yyyy-MM-dd\',maxDate:\'#F{$dp.$D(\\\'endTime'+num+'\\\')}\',isShowClear:true});"/></td>'+
		'<td style="border:1px grey solid;text-align: center;"><input name="planWorkTicketGroundwireList['+num+'].endTime" id="endTime'+num+'" style="font-size:14px; border: medium none;"  					onclick="WdatePicker({dateFmt:\'yyyy-MM-dd\',minDate:\'#F{$dp.$D(\\\'startTime'+num+'\\\')}\',isShowClear:true});"/></td>'+
		'</tr>'
注: maxDate:'#F{$dp.$D(\'txtEndDay\')}'    所以在拼接时 自带的格式中出现特殊字符的比如 '  \  等都需要转义才能保证其格式 

22.220 JQuery获取器中根据属性或属性值获得元素open in new window

1.获取页面p标签中属性有id的元素

$("p[id]")

2.根据属性值获得元素

$("input[name$='aaa']") 

获取的是name值中带有aaa的input元素的集合

3.[attribute!=value],匹配所有不含有指定的属性,或者属性不等于特定值的元素

$("input[name!='aaa']")

相当于排除input的name值等于aaa的元素,选择其他所有的元素

4.[attribute*=value],匹配给定的属性是以包含某些值的元素

$("input[name*='aaa']") 

,匹配的是input中name属性的值中包含aaa的元素,

5.[attribute^=value],匹配给定的属性是以某些值开始的元素

$("input[name^='aaa']") 

匹配input的name属性的值,是以aaa为开头的,符合这一个特征值得input元素

22.340 js 拼接/ 模板字符串

1. 模板字符串

注:jsp 写法毕竟特殊 <div id="\${type}" > 需要在 $ 符号前加 反斜杠

let name = "小芳";
let age = 13;
//传统写法
let str1 = '名字' + name + '年龄' + age;
console.log(str1);//名字小芳年龄ma13
//使用模板字符串写法
let str2 = `名字${name}年龄${age}`;
console.log(str2);//名字小芳年龄13
// 多行 的拼接
var text = ` ${name},no matter what you do,
  I trust you.`;
20210127
20210127

2. 字符串拼接

'<td  onclick="updateBusiness(\'work_person_division\',\''+data.id+'\' , \'500\');">'+   //拼接多个字段
<input type="text"  value="'+data.workPersonDivisionList[i].workContent+'"/></td>';

html+="<input  name='"+'postionZdData_'+index+"' value='"+item.value+"' onclick='initPostionZd(\""+item.value+"\");' id='checkbox-999-"+item.value+"' />";

html+= "<div class='bottomFilter8_tl'  id='zd"+item.value+"' onclick='checkedZd(\""+item.value+"\",this,\"bottomFilter8\");'>"+
"<div class='mes_close'  onclick='removePushMesPopup(\"push_mes_popup_\""+mes_html_index+"\")'><i class='icono-crossCircle'></i></div>"+

22.350 复选框

1.设置复选框大小

需要 同时设置height 和width 才会生效 <input type="checkbox" style="height: 20px; width: 20px;">

2.选中和取消选中

$(':checkbox').prop('checked', false);
$(':checkbox').prop('checked', true); // 有效
// 下面这个不一定生效
$(':checkbox').attr('checked', false);
$(':checkbox').attr('checked', true); // 无效

3.验证是否选中

//判断checkbox 是否选中
$("#id").is(":checked");//选中,返回true,没选中,返回false

案例:

该思路核心方法 是:collectionCheck和updateSelected 。每次操作复选框记录当前选中的对象。点击查询按钮时不用 做其他操作,直接取types 即可

复选框处理2中思路:

​ 1.列如本案例:collectionCheck和updateSelected 。每次操作复选框记录当前选中的对象

​ 2.执行 查询按钮时 再去获取选中的复选框,核心方法用到getCollerMenuChecked 只要在 搜素方法触发的地方调用getCollerMenuChecked 方法即可

以上2种方法的选择:

​ 如果数据比较多,用方法一

​ 数据量较少,优先选用方法二

      • ​ 如果查询按钮对应的方法,比较复杂,列如本案例,有多个tab都有搜素方法,所以不适合再查询方法中加载过多的逻辑处理,所以选用方法一
image-20210929101110516
image-20210929101110516
/* 状态巡视 菜单栏 构造*/
function addCollerctMenu() {
    var html=` <div class="middle_from_div" >
            <input type="checkbox" id="collerct-box-0" onclick="collectionCheckAll(event);" class="collerct_menu_checkbox">
            	<label for="collerct-box-0" >全选</label>
            </div>`;
    collectPopupData.forEach(e => {
        html += addCollerctMenuHtml(e);
    })
    $("#collect_menu_werp").append(html);
    // 初始 默认全部选中
    $(".collerct_menu_checkbox").prop('checked',true);
    getCollerMenuChecked();/* 初始默认勾选*/
}
function addCollerctMenuHtml(item) {
    var html=` <div class="middle_from_div" >
            	<input type="checkbox" id="collerct-box-\${item.id}" data-collectType="\${item.id}" onclick="collectionCheck(event,'\${item.id}');" class="collerct_menu_checkbox collerct_menu_checkbox_son">
            	<label for="collerct-box-\${item.id}" >\${item.name}</label>
            </div>`;
    return html;
}
var types;//复选框选中的 对象values 
var collectTypesForZtXsArr=[];// 状态巡视 复选框选中项
/* 初始默认勾选*/
var getCollerMenuChecked = function () {
    $(".collerct_menu_checkbox_son").each(function(index,item){
        var collectType = $(this).attr("data-collectType");
        //判断checkbox 是否选中
        if($(this).is(":checked")){
            collectTypesForZtXsArr.push(collectType);
        }else{
            var idx = collectTypesForZtXsArr.indexOf(collectType);
            collectTypesForZtXsArr.splice(idx, 1);
        }
    });
    types=collectTypesForZtXsArr.join(",");
}
/*状态巡视 菜单栏 复选框 单击*/
function collectionCheck(event,id) {
    var checkbox = event.target;
    var action = (checkbox.checked?'add':'remove');
    updateSelected(action,id,checkbox.name);
}
var updateSelected = function (action, id, name) {
    if (action == 'add' && collectTypesForZtXsArr.indexOf(id) == -1) {
        collectTypesForZtXsArr.push(id);
    }
    if (action == 'remove' && collectTypesForZtXsArr.indexOf(id) != -1) {
        var idx = collectTypesForZtXsArr.indexOf(id);
        collectTypesForZtXsArr.splice(idx, 1);
    }
    types=collectTypesForZtXsArr.join(",");
    // checkPopupMenuCallback(collectTypesForZtXsArr.join(","));
    console.log(types);
};
/*全选*/
function collectionCheckAll(event){
    if($(event.target).is(":checked")){// 全选
        console.log("全选");
        $(".collerct_menu_checkbox").prop('checked',true);
    }else{//取消选中
        $(".collerct_menu_checkbox").prop('checked',false);
    }
    getCollerMenuChecked();
}

22.370 js 中 字符串和数值 的转换

// 字符串转 数字
parseFloat("123");




22.400 js计算坐标 之间的距离

function toRad(d) {
    return d * Math.PI / 180;
}
function getDisance(lng1,lat1,lng2 , lat2) { //lat为纬度, lng为经度, 一定不要弄错
    var dis = 0;
    var radLat1 = toRad(lat1);
    var radLat2 = toRad(lat2);
    var deltaLat = radLat1 - radLat2;
    var deltaLng = toRad(lng1) - toRad(lng2);
    var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
    return dis * 6378137;
}
alert(  getDisance(119.84411419,29.98447129,119.84419419,29.98447129) );
var jdxForTowerMap={};// 分组 合并 将重叠的放一起
var cdItem = [];// 存储 被验证的重叠的 的对象,依次 比对,如果两两 重叠则 讲被比对象 放到 该数组中,后期 需要跳出 该对象的 比对
console.log(jdxJsonArr)
outer_loop:for (var i = 0; i < jdxJsonArr.length; i++) {
	var item= jdxJsonArr[i];
	if(cdItem.indexOf(item.id)!=-1){// 说明当前 对象 已经 和其他对象验证 重叠了,不用再去拿他 重新比较了
		continue outer_loop;// 跳出外循环 本下循环,执行下一次循环
	}
	if(jdxForTowerMap[i] == undefined){
		jdxForTowerMap[i] = [];
	}
	jdxForTowerMap[i].push(item);
	// 内层循环,比对 是否存在和当前 对象 距离很近的对象
	inner_loop:for (var j = i+1; j < jdxJsonArr.length-i-1; j++) {
		var item1= jdxJsonArr[j];
		var disance=getDisance(item.nowLongGps,item.nowLatGps,item1.nowLongGps,item1.nowLatGps);
		if(disance < 1){// 如果两点 之间 距离小于 10m ,则认为其是 重叠在一起,需要 归为一类,
			cdItem.push(item1.id);// 记录被比数值,下次循环 不用拿他再去 和其他对象比对了
			jdxForTowerMap[i].push(item1);
		}
	}
}

22.410 滚动条--滑块

基于Bootstrap的jQuery slider插件的使用bootstrap-slider.js

https://blog.csdn.net/u011127019/article/details/52992654open in new window

https://www.jq22.com/yanshi9075open in new window

###################
       HTML
###################

<input id="ex4" type="text" data-slider-min="-5" data-slider-max="20" data-slider-step="1" data-slider-value="-3" data-slider-orientation="vertical"/>

data-slider-orientation="vertical" 用来控制 滚动条的方向
###################
    JavaScript
###################

// With JQuery
$("#ex4").slider({
	reversed : true
});

// Without JQuery
var slider = new Slider("#ex4", {
	reversed : true
});

22.420 js 克隆

https://www.cnblogs.com/hubgit/p/6859910.htmlopen in new window

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
    <style>
    .left,
    .right {
        width: 300px;
        height: 120px;
    }
    
    .left div,
    .right div {
        width: 100px;
        height: 90px;
        padding: 5px;
        margin: 5px;
        float: left;
        border: 1px solid #ccc;
        background: #bbffaa;
    }
    </style>
</head>

<body>
    <h2>通过clone克隆元素</h2>
    <div class="left">
        <div class="aaron1">点击,clone浅拷贝</div>
        <div class="aaron2">点击,clone深拷贝,可以继续触发创建</div>
    </div>
    <script type="text/javascript">
        //只克隆节点
        //不克隆事件
        $(".aaron1").on('click', function() {
            $(".left").append( $(this).clone().css('color','red') )
        })
    </script>

    <script type="text/javascript">
        //克隆节点
        //克隆事件
        $(".aaron2").on('click', function() {
            console.log(1)
            $(".left").append( $(this).clone(true).css('color','blue') )
        })
    </script>
</body>

</html>

22.420 js 退出循环

  • break
  • continue: 跳出本次循环,执行下次循环
  • return

案例:双层循环

//loop_1用于对循环命名
 loop_1:for(var i=0;i<10;i++){
    loop_2:for(var j=0;j<5;j++){
         if(i==3 && j==4){
            break loop_1;//跳出循环loop_1
         }
     }
 }
 alert(i);//输出3

22.421 js 退出循环并返回数值

data = ['fwaf','gagw0','fwagw','gawg']

    function test(index){
        var ret = null
        $.each(data,function (k,v) {
            if(k == index){
                ret = data[k]    #在循环中将数据赋给我们定义的局部变量
                return false    #遇到返回false,跳出循环
            }
        })
        return ret    #返回数据
    }
getGraphicById=function(graphicsLayer,id){
    var return_graphic;
    var graphicArr = graphicsLayer.graphics;
    jQuery.each(graphicArr, function (index, graphic) {
        if (graphic.id == id) {
            return_graphic=graphic
            return true;
        }
    });
    return return_graphic;
}

22.430 layer

  • 提示框
layer.msg('同上', {
  icon: 1,
  time: 2000 //2秒关闭(如果不配置,默认是3秒)
}, function(){
  //do something
});
  • 1) layer iframe 弹出窗,相对浏览器定位,可以用top.layer
var h = (window.innerHeight-10)+"px";
var w = (window.innerWidth/3*2)+"px";
top.layer.open({
		 type: 2, 
		 title: ['详情', 'font-size:18px;'],
		 area: [w, h],
		 offset: '80px',// 距离浏览器 顶部位置
		 anim: 0,
		 content: "${ctx}/msg/msgNewsInfo/formdetail2?id="+id 
//这里content是一个URL,如果你不想让iframe出现滚动条,你还可以content: ['http://sentsin.com', 'no']
	}); 

22.440 表单提交验证

<HTML>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <BODY>
        <form action="http://www.baidu.com" onsubmit="return toVaild()">
            <input type="text" id="ff">
            <input type="submit" id="submit" value ="提交"/>
        </form>
    </BODY>
        <script language="javascript">
            function toVaild(){
                var val = document.getElementById("ff").value;
                alert(val);
                if(val == "可以提交"){
                    alert("校验成功,之后进行提交");
                    return true;
                }
                else{
                    alert("校验失败,不进行提交");
                    return false;
                }
            }
    </script>
</HTML>

22.450 Math函数

// 求2的开根号
function mySqrt(num){
		return Math.log(num)/Math.log(2);
}

22.500 ztree

zTree 收缩的两种方式

  • 方式1:对现有节点进行模糊匹配
var setting = {
            data: {
                simpleData: {enable: true,idKey: "id",pIdKey: "pId",rootPId: 0}
            },
            /*view: {
                expand:true,
                dblClickExpand: false,
                showLine: true
            },*/
            view: {
                fontCss: setFontCss_ztree ,
                showTitle :true
            },
            async:{enable:true,url:"${ctx}/map/dp/treeTowerData1?type=3",autoParam:["id=lineId","pId=officeId"]},
            callback:{
                onClick:function(event, treeId, treeNode){
                    var id = treeNode.id == '0' ? '' :treeNode.id;
                }
            }
        };
// 异步加载
function refreshTree(){
            $.getJSON("${ctx}/map/dp/treeLineData?type=1",function(data){///map/dp/treeLineData?type=1  ${ctx}/sys/office/treeData?type=6
                initZtree(data);
            });
        } 
var initZtree=function(data){
            tree = $.fn.zTree.init($("#tower_ztree"), setting, data);
            var nodes = tree.getNodesByParam("level", 0);
            for(var i=0; i<nodes.length; i++) {
                tree.expandNode(nodes[i], true, false, false);
            };
        };
        var searchtree = function(){
            var value = $("#search-input").val();
            var nodes = tree.getNodes();
            if (value == "") {
                refreshTree();
                return;
            }
            hideAllNode(nodes);
            var nodeList = tree.getNodesByParamFuzzy("name",value);
            updateNodes(nodeList);
        };
        //隐藏所有节点
        function hideAllNode(nodes){
            nodes = tree.transformToArray(nodes);
            for(var i=nodes.length-1; i>=0; i--) {
                tree.hideNode(nodes[i]);
            }
        }
        //更新节点状态
        function updateNodes(nodeList) {
            tree.showNodes(nodeList);
            for(var i=0, l=nodeList.length; i<l; i++) {
                //展开当前节点的父节点
                tree.showNode(nodeList[i].getParentNode());
                //显示展开符合条件节点的父节点
                while(nodeList[i].getParentNode()!=null){
                    tree.expandNode(nodeList[i].getParentNode(), true, false, false);
                    nodeList[i] = nodeList[i].getParentNode();
                    tree.showNode(nodeList[i].getParentNode());
                }
                //显示根节点
                tree.showNode(nodeList[i].getParentNode());
                //展开根节点
                tree.expandNode(nodeList[i].getParentNode(), true, false, false);
            }
        }

构造 ztree 熟结构PC端

	private String id;
	private String name;
	private String pId;
	private String iconSkin;
	private String isParent;// mybatis 不支持 boolen
	
	对应的sql
	SELECT t.id AS "id",
        t.tower_NAME AS "name",
        t.line_id AS "pId",
        'false' as "isParent"
    from bas_c_tower t

22.510 template.js模板引擎

js 模板引擎:https://aui.github.io/art-template/zh-cn/docs/installation.htmlopen in new window

https://www.cnblogs.com/w190/p/12890341.htmlopen in new window

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>模板引擎</title>
		<script type="text/javascript" src="template.js"></script>
		<script type="text/html" id="resultTemplate">
			<h1>{{title}}</h1> {{each books as value i}}
			<div>{{value}}</div>
			{{/each}}
		</script>

		<script type="text/javascript">
			window.onload = function() {
				//模拟这个data数据是从服务器获取的数据
				//这个数据中有两个字段:一个是title,一个是books
				var data = { //data数据
					title: '四大名著图书信息',
					books: ['三国演义', '水浒传', '西游记', '红楼梦']
				};
				//template根据两个参数生成html片段保存在html里面
				//这里也就是把data数据保存到id为resultTemplate的template模板中去。
				var html = template("resultTemplate", data); //第一个参数是模板的id,第二个参数是data数据
				var container = document.querySelector("#container");
				container.innerHTML = html;
			}
		</script>

	</head>

	<body>
		<div id="container">

		</div>
	</body>

</html>

22.520 获取光标位置

var getScreen=function(event){
            var e = event || window.event;
            //return {'x':e.screenX,'y':e.screenY} // 相对于整个浏览器 而不是文档
            return {'x':e.pageX,'y':e.pageY}
        }

22.530 弹窗层

说明:

  • 页面 定义父容器 class='html_wrap'
  • 页面需要自定义 弹窗回调:popupCheck
  • 功能参考巡检保 jkzxModuleHomeView.jsp
image-20210512101200184
image-20210512101200184
  • css 部分
/* 自定义弹出层*/
.popup_wrap{
   /* height: 200px;
    width: 150px;*/
    box-shadow: 0 0 10px #4a90d8 inset, 0px 0px 30px rgb(0,153,184);
    font-family: Microsoft YaHei;
    font-size: 1.2em;
    font-weight: 600;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    cursor: pointer;
    background: rgb(0,0,0,0.8);
    color: #f4f4f4;
    border-radius: 5px;
    opacity: 0;
    left: 0px;
    top: 0px;
    padding: 10px;
}
.popup_wrap .item{
    padding: 5px 0;
    transition: all 0.6s;
    display: flex;
    align-items: center;
    justify-content: center;
}
.popup_wrap .item:hover{
    color: #13c3e3;
    background: #0e3056;
    /*transform: scale(1.1);*/
}
.popup_icon{
    padding-right: 10px;
}
  • js 部分
//================================================# 1.弹出层 #================================================
/**
    页面 定义父容器 class='html_wrap'
    页面需要自定义 弹窗回调:popupCheck
        功能参考 jkzxModuleHomeView.jsp
 */
/* 创建弹窗  */
var popover_width = 150;
var popover_height = 200;
var initPopupHTML = function(popupData,event,callback){
    var screen = getScreen(event);// 计算 鼠标位置
    if($(".popup_wrap").length>0){
        $(".popup_wrap").remove();
    }
    /* 弹出 先设置透明度为0 实现隐藏 ,然后用animate 设置 动画 从而 实现 弹窗的弹出*/
    var html =`<div id="popup_wrap" class="pa popup_wrap bs" style="left:${screen.x}px;top:${screen.y}px;width:${popover_width}px;height: ${popover_height}px">`+
                `<div class="resultHtml wh100 bs">`;
    jQuery.each(popupData, function (index, item) {
        var check=item.check==undefined?'':item.check;// 实现默认选中
        html+=      `<div id="${item.id}" title="${item.name}" class="item ${check}" onclick="popupCheck('${item.id}','${item.name}',${callback})">`;
        if(item.icon){
            html+=      `<img class="popup_icon zdy_popup_icon" title="" src="${item.icon}">`;// 预留 zdy_popup_icon 属性 供调用者 设置 自定义属性 样式
        }
        html+=`<div>${item.name}</div>`+
            `</div>`;
    });
    html+=`</div></div>`;
    $(".html_wrap").append(html);// html_wrap 整个页面 的 父容器
    // 设置高度(考虑如果数据太少 弹窗 显示不协调)
    if(popupData.length<=5){
        $(".popup_wrap").height(popupData.length*30+20);
    }

    openPopover(screen,event)// // 弹出 弹窗
}

/* 获取*/
var getScreen=function(event){
    var e = event || window.event;
    //return {'x':e.screenX,'y':e.screenY} // 相对于整个浏览器 而不是文档
    var popover_top=e.pageY+5;
    var popover_left=e.pageX+10;
    var window_width = $(".html_wrap").width();
    var window_height = $(".html_wrap").height();
    // 验证 是否 超出 父容器 右侧 用 弹窗 left(popover_left) + 弹窗宽度 popover_width 和 父容器 的宽度 比对
    if(popover_width+popover_left>=window_width){// 超出父容器,宽度 需要重新计算
        popover_left = window_width-popover_width-20;//用 父容器 宽度 - 弹窗宽度,在减去 一个padding =20
    }
    if(popover_height+popover_top>=window_height){// 超出父容器,高度 需要重新计算
        popover_top = window_height-popover_height+20;//用 父容器 宽度 - 弹窗宽度,在减去 一个padding =20
    }
    return {'x':popover_left,'y':popover_top}
}
// 弹出 弹窗
var openPopover = function(screen,event){
    event.stopPropagation();//用于定义 弹窗,点击其他区域 隐藏  弹窗,防止
    $(".html_wrap").addClass('popover-open');// 给 父元素 标记  ‘当前弹出窗口模式’
    // 需要 考虑,弹窗不能超出 父容器
    $("#popup_wrap").animate({
        //left:screen.x+'px',
        //top:screen.y+'px',
        opacity:"1"
    },600);
}


/* 关闭弹窗*/
var closePopover = function(){
    if($(".popup_wrap").length>0){
        $(".popup_wrap").remove();
        $(".html_wrap").removeClass('popover-open');// 为了实现 点击其他区域 关闭弹窗,对父节点 jkxz_div 定义 class 属性 popover-open 表示当前 弹窗激活
    }
}
function popupCheck(id,name,callback){
    closePopover();/* 关闭弹窗*/
    callback(id,name);
}
/* 弹出 默认选中*/
var resetCheckPopover = function(options,selectedId){
    jQuery.each(options, function (index, item) {
        if(selectedId==item.id){
            item.check='check';
        }else{
            item.check='';
        }

    });
}
/*
*   点击其他区域关闭弹窗
*       当前方法实现 的大前提,对于 openPopover 弹出层
*           需要使用 event.stopPropagation(); 阻止冒泡,否则 弹出还未谈起就被关闭
* */
$(document).click(function(){
    if($(".html_wrap").hasClass('popover-open')){
        closePopover();/* 关闭弹窗*/
    }
    // 调用 父页面 方法
    // 验证 父页面是否存在 弹窗 通过 是否存在 html_wrap 元素
    if($(".html_wrap", parent.document).length>0){
        // 父页面存在弹窗,,点击也需要关闭
        window.parent.closePopover();
    }
    // 验证子页面是否存在 弹窗
    if(document.getElementById("mainFrame") !=null && $('#mainFrame').contents().find(".html_wrap").length>0){
        // 子页面存在弹窗,,点击也需要关闭
        var ifra = document.getElementById("mainFrame");
        ifra.contentWindow.closePopover();
    }
});

  • 调用者
<script>
     var relativeUrlPath = '${ctxStatic}/images/jkzx/';
        var  pageSizeOptions = [
            {id:1,name:'一张',icon:relativeUrlPath+'small_icon/split_screen_1.png'},
            {id:4,name:'四张',icon:relativeUrlPath+'small_icon/split_screen_4.png'},
            {id:6,name:'六张',icon:relativeUrlPath+'small_icon/split_screen_6.png'},
            {id:9,name:'九张',icon:relativeUrlPath+'small_icon/split_screen_9.png'}
        ];
        /* 滚动时间*/
        var chooseTimeOptions = [
            {id:10,name:'10s'},
            {id:20,name:'20s'},
            {id:30,name:'30s'},
            {id:40,name:'40s'},
            {id:50,name:'50s'}
        ];
    
    
    
    
        var showPopover=function(type,event){
            var popupData=[];
            if(type=='officeType'){
                popupData=officeData
            }else if(type=='arrangeType'){
                popupData = pageSizeOptions;// 分屏
            }else if(type=='chooseType'){
                popupData = chooseTimeOptions;// 时间
            }
            initPopupHTML(popupData,event); /* 创建弹窗  */
        }


        function popupCheck(id,name){
            closePopover();/* 关闭弹窗*/
            alert('选择弹窗内容')
        }
</script>

22.540 Json对象与Json字符串的转化、JSON字符串与Java对象的转换open in new window(关键字:list转json )

参考:https://www.cnblogs.com/test-7/p/10144683.htmlopen in new window

JS中将后台model传过来的数据转换成JSON类型____ [ {key,value},{key,value},{key,value} ] 是list格式,如果在js中无法便利 那么就用下面的方法处理一下 (list页面遍历,list遍历,list遍历)

JAVA 中:model.addAttribute("datasJson", new Gson().toJson(mapList));

JS中:var data = eval(${datasJson });///用JSON.parse() 也可以转换

${fns:toJson(list)} JsonMapper.java 有一些将实体对象转为数组的方法

////可以用 标签遍历

一.Json对象与Json字符串的转化

1.jQuery插件支持的转换方式:
  $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符串转换成json对象
2.浏览器支持的转换方式(Firefox,chrome,opera,safari,ie9,ie8)等浏览器:
  JSON.stringify(obj)将JSON转为字符串。JSON.parse(string)将字符串转为JSON格式;
var a={"name":"tom","sex":"男","age":"24"}; 
var b='{"name":"Mike","sex":"女","age":"29"}'; 
var aToStr=JSON.stringify(a); 
var bToObj=JSON.parse(b); 
alert(typeof(aToStr));  //string 
alert(typeof(bToObj));//object

3.Javascript支持的转换方式: 
eval('(' + jsonstr + ')'); //可以将json字符串转换成json对象,注意需要在json字符外包裹一对小括号 
注:ie8(兼容模式),ie7和ie6也可以使用eval()将字符串转为JSON对象,但不推荐这些方式,这种方式不安全eval会执行json串中的表达式。

4.JSON官方的转换方式: 
http://www.json.org/提供了一个json.js,这样ie8(兼容模式),ie7和ie6就可以支持JSON对象以及其stringify()和parse()方法; 
可以在https://github.com/douglascrockford/JSON-js上获取到这个js,一般现在用json2.js。

二、JSON 字符串 与 java 对象的转换
1. 把java 对象列表转换为json对象数组,并转为字符串
    JSONArray array = JSONArray.fromObject(list);
    String jsonstr = array.toString();
2. 把java对象转换成json对象,并转化为字符串

  JSONObject object = JSONObject.fromObject(user);
  Log4jInit.ysulogger.debug(object.toString());
3.把JSON字符串转换为JAVA 对象数组
  JSONArray json = JSONArray.fromObject(userStr);//userStr是json字符串
  List<User> users= (List<User>)JSONArray.toCollection(json, User.class);
4.把JSON字符串转换为JAVA 对象
  JSONObject jsonobject = JSONObject.fromObject(jsonStr);
  User user= (User)JSONObject.toBean(object,User.class);

元素自定义属性

这种方式需要在自定义属性名前面加上data-

<div id="{{item.id}}" data-item="{{item}}" class="pic_check_box check" onclick="switchCheck(this);"></div>

<script>
var towerIdArr = [];// 被选中  towerid
var equipidArr = [];// 被选中 设备id
var filepathArr = [];// 被选中 选中图片id
$(".pic_check_box").each(function(){
    if($(this).hasClass("check")){// 选中
        var item = JSON.parse($(this).attr("data-item"));
        towerIdArr.push(item.towerId);
        equipidArr.push(item.equipid);
        filepathArr.push(item.filepath);
    }
});
</script>

22.560 js复制 文字和图片

参考: https://stackoverflow.com/questions/33175909/copy-image-to-clipboard/40547470#40547470open in new windowhttps://segmentfault.com/a/1190000015278418open in new window

使用clipboard.js,有两个限定

1.只复制目标节点的子节点,对于img标签,如果不额外包裹一层父元素,无法实现图片复制

2.只接受click事件,无法绑定其他事件。

方法1

<!DOCTYPE html>
<html>
 <head> 
  <title>复制</title> 
  <meta name="referrer" content="never" /> 
  <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script> 
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
 </head> 
 <body> 
  <div id="copyimg" class="copyable" style="height:100px;width:100px;"> 
   <img style="width:100%;height:100%;" src="http://172.16.10.244:2166/pic/20210525/86471603036765600_20210525T112046.jpg" alt="" /> 
  </div> 
  <div class="wechat-copy" onclick="copyImg('copyimg',event);"> 
   <button style="color:#FFFFFF;background-color: #263740">复制</button> 
  </div> 
  <script type="text/javascript">
   
    function SelectText(element) {
            var doc = document;
            if (doc.body.createTextRange) {
                var range = document.body.createTextRange();
                range.moveToElementText(element);
                range.select();
            } else if (window.getSelection) {
                var selection = window.getSelection();
                var range = document.createRange();
                range.selectNodeContents(element);
                selection.removeAllRanges();
                selection.addRange(range);
            }
        }
      // 方法一 监听 事件
        $(".copyable").click(function (e) {
            //Make the container Div contenteditable
            $(this).attr("contenteditable", true);
            //Select the image
			
            SelectText($(this).get(0));
            //Execute copy Command
            //Note: This will ONLY work directly inside a click listenner
            document.execCommand('copy');
            //Unselect the content
            window.getSelection().removeAllRanges();
            //Make the container Div uneditable again
            $(this).removeAttr("contenteditable");
            //Success!!
            alert("image copied!");
        });
      // 方法二 定义 onclick 事件,通过传递目标 元素 id
      function copyImg(id,event){
            $("#"+id).attr("contenteditable", true);
            //Select the image
            SelectText($("#"+id).get(0));
            //注意:这将只在点击侦听器中直接工作
            document.execCommand('copy');
            //取消选择的内容
            window.getSelection().removeAllRanges();
            //再次使容器Div不可编辑
            $("#"+id).removeAttr("contenteditable");
            //成功提示
            alertx("图片已复制到剪切板!");
        }
</script>   
 </body>
</html>
坑1:复制时想保留换行,input不会保留换行,换成textarea后成功
坑2:换成textarea后使用setAttribute('value','')复制失败,换成textarea.value后成功
坑3:复制时想保留value里的换行,尝试\r\n,<br/>,\r后发现使用\r成功
<button id="btn"  style="margin-top: 40px;">一键复制</button>

const btn = document.querySelector('#btn');
        btn.addEventListener('click', () => {
            const textarea= document.createElement('textarea');
            textarea.setAttribute('readonly', 'readonly');
            textarea.value = '姓名:肖敏\r性别:女\r年龄:23';
            document.body.appendChild(textarea);
            textarea.select();
            if (document.execCommand('copy')) {
                document.execCommand('copy');
                alert('复制成功');
            }
            document.body.removeChild(textarea);
        })

方法2

<!DOCTYPE html>
<html>
<head>
	<title>复制</title>
	 <meta name="referrer" content="never">
	<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

</head>
<body>
<div id='wechat-copy-main' style="opacity: 0">
<img class='img' src='https://tenfei04.cfp.cn/creative/vcg/veer/1600water/veer-308325838.jpg' style='width:50px;'><br/>
</div>
<br />
<span class="wechat-copy">
   <button style="color:#FFFFFF;background-color: #263740">复制</button>
</span>
<script type="text/javascript">
   
    $(".wechat-copy").click(function (t) {
        //$('.img').attr('src','https://tenfei04.cfp.cn/creative/vcg/veer/1600water/veer-308325838.jpg');
        var a = document.getElementById("wechat-copy-main");
        console.log(a);
        copyFunction(a, ".wechat-copy", "微信文案复制成功");
    });
    var copyFunction = function (t, a, i) {
		var e = new ClipboardJS(a, {
			target: function () {
				return console.log(t, a),
					t
			}
		});
		e.on("success", function (t) {
				alert('文案复制成功!');
				t.clearSelection()
		}),
		e.on("error", function (t) {
			console.log('复制失败');
				t.clearSelection()
		})
    };

</script>

</body>
</html>

vue

    copyToClipboard() {
      const text = this.$refs.textToCopy.innerText; // 获取文本内容
      const textarea = document.createElement('textarea');
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy'); // 执行复制操作
      document.body.removeChild(textarea);
      
      this.isCopied = true;  // 显示“已复制”提示
      setTimeout(() => {
        this.isCopied = false; // 3秒后隐藏提示
      }, 3000);
    }

22.570 jQuery动画

**使用animate 动画 ,如果设置的元素存在pading ,就算 将元素的width 设置为0 也不会 使元素空间释放出来,这里可以用 hide()来实现 隐藏并释放空间 **

自定义动画animate()

参考:https://www.w3school.com.cn/jquery/effect_animate.aspopen in new window

$(selector).animate(styles,speed,easing,callback)

animate() 方法执行 CSS 属性集的自定义动画。

该方法通过CSS样式将元素从一个状态改变为另一个状态。CSS属性值是逐渐改变的,这样就可以创建动画效果。

只有数字值可创建动画(比如 "margin:30px")。字符串值无法创建动画(比如 "background-color:red")。

**注释:**使用 "+=" 或 "-=" 来创建相对动画(relative animations)。

支持 使用 百分比 $("p").animate({width:"50%"});

参数描述
styles必需。规定产生动画效果的 CSS 样式和值。可能的 CSS 样式值(提供实例):**注释:**CSS 样式使用 DOM 名称(比如 "fontSize")来设置,而非 CSS 名称(比如 "font-size")、marginTop、paddingLeft........
speed可选。规定动画的速度。默认是 "normal"。可能的值:毫秒 (比如 1500)"slow""normal""fast"
easing可选。规定在不同的动画点中设置动画速度的 easing 函数。内置的 easing 函数:swinglinear扩展插件中提供更多 easing 函数。
callback可选。animate 函数执行完之后,要执行的函数。

参考:https://blog.csdn.net/a772116804/article/details/81909073open in new window

// animate():第一个参数:{width:200} 运动的值和属性 // 第二个-时间:默认400ms{},1000 //第三个-运动形式-两种:1.默认:swing(慢快慢) 2.linear(匀速) //第四个-回调函数 //$(this).animate({width:"300px",height:"300px"},2000,'linear',function(){alert(123)});

//stop():默认阻止当前运动,不阻止所有,stop(true) 阻止后续所有运动,stop(true,true) 当前运动立马完成 = finish()立即完成运动。

stop(true,true) 停止到最终的目标点

finish() 立即完成运动。

运动前加stop()可以清除运动队列(不总是重复)。(鼠标移入移除 mouseover、out)

$(this).stop().animate({width:'200px'},1000) //针对的是同一个元素上面的效果

jq animate动画详解

//动画延迟
.leftToRight{
    left:0;
}
$('.leftToRight').delay(800).animate({left:100px},"solw");
 
animated方法中没有封装transform属性
 
解决方案:
(1)css方法
 
$($sub).animate({},5000,function(){  
    $(this).css({'transform':'translateX(300px)'});  
})  
在动画函数的回调函数里执行。时间和效果就没了意义,毕竟函数是在动画完成之后才有调用
 
(2)addClass方法
可以通过addClass()方法来代替此动作: 
比如想旋转一个icon 
在css中加入一个class
Css代码
.add_transform{  
    transform:rotate(180deg);  
    -ms-transform:rotate(180deg);/* IE9 */  
    -moz-transform:rotate(180deg);/* Firefox */  
    -webkit-transform:rotate(180deg);/* Safari和Chrome */  
    -o-transform:rotate(180deg);/* Opera */  
    transition:all 0.5s ease-in-out;  
    -moz-transition:all 0.5s ease-in-out;/*Firefox 4 */  
    -webkit-transition:all 0.5s ease-in-out;/* Safari和Chrome */  
    -o-transition:all 0.5s ease-in-out;/* Opera */  
}  
 然后通过$(“选择器”).toggleClass(“.add_transform”);来使icon的旋转变为动画效果。
 
 <script>
//jQuery动画animate和scrollTop结合使用
$('li').click(function(){
    //$(document).scrollTop($(this).index()*viewHeight);
     var H = $(this).index()*viewHeight;
     var heiGht = $('#div1').offset().top;
     $('html,body').animate({scrollTop: H}, 1000);
  });
</script>
 
<body>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<style>
 #box { 
  width: 100px; 
  height: 100px; 
  background-color: red; 
 
  position:absolute; 
} 
 
#pox { 
  width: 100px; 
  height: 100px; 
  background-color: green; 
  position: absolute; 
  top: 200px; 
} 
</style>
</head>
<body>
	<input type="button" class="button" value="开始" />
	<input type="button" class="stop" value="停止" /> 
	    
	  <div id="box">box</div> 
	  <div id="pox">pox</div> 
<script type="text/javascript">
	 $(function () {   
	    $(".button").click(function () { 
	      $("#box").animate({ 
	        left: "300px"  //要想使用left top bottom right这种方向性的属性 先必须对"#box元素设置CSS 绝对定位 
	      }) 
	    })  
   
    //-------------------------------------同步动画  
    $(".button").click(function () { 
      $("#box").animate({ 
        width: "300px", 
        height: "200px", 
        opacity:0.5, //透明度为0.5 注:透明度的值在0-1之间 
        fontSize:"200px", //字体大小设为30px 
      }) //第一个参数:是一个对象,他是键值对的css 
    }) 
 
    //让指定元素左右移动
    $("#right").click(function(){
      $(".block").animate({left: '+50px'}, "slow");
    });
 
    $("#left").click(function(){
      $(".block").animate({left: '-50px'}, "slow");
    });
 
	//--------------------------------------列队动画,一个一个来 
    $(".button").click(function () { 
      $("#box").animate({ width: "300px"}, 1000, function(){ 
        $("#box").animate({height:"200px"},1000,function(){ 
          $("#box").animate({opacity:0.5},1000,function(){ 
            $("#box").animate({fontSize:"150px"},1000,function(){alert("完毕")}) 
          }); 
        }); 
      }); 
    }) 
 
	//在同一个元素的基础上,使用链式(队列)调用也可以实现列队动画 
 
    $(".button").click(function () { 
      $("#box") 
        .animate({ width: "300px" }, 1000) 
        .animate({ height: "200px" }, 1000) 
        .animate({ opacity: 0.5 }, 1000) 
        .animate({ fontSize: "150px" }, 1000, function () { alert("列队动画执行完毕")}) 
    }); 
	
	//那我们现在的需求是:不管你有几个元素,我都要他们依次实现列队动画效果。(测试了一下,只能用这种回调函数嵌套的方式来实现了) 
  
    $(".button").click(function () { 
      $("#box").animate({ width: "300px" }, 1000, function () { //box
        $("#pox").animate({ height: "200px" }, 1000, function () { //#pox
          $("#box").animate({ height: "200px"}, 1000, function () { 
            $("#pox").animate({ fontSize: "150px" }, 1000, function () { alert("列队动画执行完毕") }); 
          }) 
        }) 
      }) 
    }) 
	
	//那下面再来了解下,列队动画的停止 
      
    $(".button").click(function () { 
      $("#box")
      .animate({ left: "300px" },1000) 
      .animate({ bottom: "300px" }, 1000) 
      .animate({ width: "300px" }, 1000) 
      .animate({ height: "300px" }, 1000)                   
    }) 
  
    $(".stop").click(function () { 
     	$("#box").stop(true); // 加参数停止所有动画,不加停止当前 
    }) 
 
 //现在,我们想继续在.queue()方法后面再增加一个隐藏动画,这时发现居然无法实现。
/*这是.queue()特性导致的。
有两种方法可以解决这个问题,jQuery 的.queue()的回调函数可以传递一个参数,
这个参数是next 函数,在结尾处调用这个next()方法即可再链式执行列队动画。 
  */
    //链式编程实现队列动画 
    $(".button").click(function () { //四个动画 
      $("#box") 
        .slideUp(1000) 
        .slideDown(1000) 
        .queue(function (next) { //这个next是一个函数 
        $(this).css("background", "yellow"); 
        next();}) 
        .hide(1000); 
    }); 
  
    //顺序编程实现队列动画 我们看到使用顺序调用的列队,逐个执行,非常清晰 
    $(".button").click(function () { 
      $("#box").slideUp(1000); 
      $("#box").slideDown(1000); 
      $("#box").queue(function (next) { 
      	$(this).css("background", "yellow"); 
    	next(); }); 
      $("#box").hide(1000); 
    }); 
  });
	</script>
</body>

jQuery基础(动画篇 animate,显示隐藏,淡入淡出,下拉切换

https://www.cnblogs.com/mibear/p/6850440.htmlopen in new window

1.jQuery中隐藏元素的hide方法

$elem.hide()

让页面上的元素不可见,一般可以通过设置css的display为none属性。但是通过css直接修改是静态的布局,如果在代码执行的时候,一般是通过js控制元素的style属性,这里jQuery提供了一个快捷的方法.hide()来达到这个效果

搭配duration: 3000, 从而实现 动画效果

提供参数:

.hide( options ) 当提供hide方法一个参数时,.hide()就会成为一个动画方法。.hide()方法将会匹配元素的宽度,高度,以及不透明度,同时进行动画操作

 $("button:last").click(function() {
     $("#a2").hide({
         duration: 3000,
     })
});
2.jQuery中显示元素的show方法

hide是让元素显示到隐藏,show则是相反,让元素从隐藏到显示

  • show与hide方法是修改的display属性,通过是visibility属性布局需要通过css方法单独设置
  • 如果使用!important在你的样式中,比如display: none !important,如果你希望.show()方法正常工作,必须使用.css('display', 'block !important')重写样式
  • 如果让show与hide成为一个动画,那么默认执行动画会改变元素的高度,高度,透明度
3.jQuery中显示与隐藏切换toggle方法 (没有动画效果)

基本的操作:toggle();

这是最基本的操作,处理元素显示或者隐藏,因为不带参数,所以没有动画。通过改变CSS的display属性,匹配的元素将被立即显示或隐藏,没有动画。

  • 如果元素是最初显示,它会被隐藏
  • 如果隐藏的,它会显示出来

display属性将被储存并且需要的时候可以恢复。如果一个元素的display值为inline,然后是隐藏和显示,这个元素将再次显示inline

提供参数:.toggle( [duration ] [, complete ] )

同样的提供了时间、还有动画结束的回调。在参数对应的时间内,元素会发生显示/隐藏的改变,在改变的过程中会把元素的高、宽、不透明度进行一系列动画效果。这个元素其实就是show与hide的方法

 $("button:last").click(function() {
        $(".right").toggle(3000)
    });
4.jQuery中下拉动画slideDown

.slideDown():用滑动动画显示一个匹配元素

.slideDown()方法将给匹配元素的高度的动画,这会导致页面的下面部分滑下去,弥补了显示的方式

常见的操作,提供一个动画是时间,然后传递一个回调,用于知道动画是什么时候结束

.slideDown( [duration ] [, complete ] )

持续时间(duration)是以毫秒为单位的,数值越大,动画越慢,不是越快。字符串 'fast' 和 'slow' 分别代表200和600毫秒的延时。如果提供任何其他字符串,或者这个duration参数被省略,那么默认使用400 毫秒的延时。

具体使用:

$("ele").slideDown(1000, function() {
    //等待动画执行1秒后,执行别的动作....
});

注意事项:

  • 下拉动画是从无到有,所以一开始元素是需要先隐藏起来的,可以设置display:none
  • 如 果提供回调函数参数,callback会在动画完成的时候调用。将不同的动画串联在一起按顺序排列执行是非常有用的。这个回调函数不设置任何参数,但是 this会设成将要执行动画的那个DOM元素,如果多个元素一起做动画效果,那么要非常注意,回调函数会在每一个元素执行完动画后都执行一次,而不是这组 动画整体才执行一次
 $("button:last").click(function() {
            $("#a2").slideDown(3000,function(){
                alert('动画执行结束')
            })
        });

5.jQuery中上卷动画slideUp

最简单的使用:不带参数

$("elem").slideUp();

这个使用的含义就是:找到元素的高度,然后采用一个下滑动画让元素一直滑到隐藏,当高度为0的时候,也就是不可见的时,修改元素display 样式属性被设置为none。这样就能确保这个元素不会影响页面布局了

带参数:

.slideUp( [duration ] [, easing ] [, complete ] )

同样可以提供一个时间,然后可以使用一种过渡使用哪种缓动函数,jQuery默认就2种,可以通过下载插件支持。最后一个动画结束的回调方法。

因为动画是异步的,所以要在动画之后执行某些操作就必须要写到回调函数里面,这里要特别注意

  $("button:last").click(function() {
            $("#a2").slideUp(3000,function(){
                alert('动画执行结束')
            })
        });

6.jQuery中上卷下拉切换slideToggle

jQuery提供了一个便捷方法slideToggle用滑动动画显示或隐藏一个匹配元素

基本的操作:slideToggle();

这是最基本的操作,获取元素的高度,使这个元素的高度发生改变,从而让元素里的内容往下或往上滑。

提供参数:.slideToggle( [duration ] ,[ complete ] )

同样的提供了时间、还有动画结束的回调。在参数对应的时间内,元素会完成动画,然后出发回调函数

同时也提供了时间的快速定义,字符串 'fast' 和 'slow' 分别代表200和600毫秒的延时

注意:

  • display属性值保存在jQuery的数据缓存中,所以display可以方便以后可以恢复到其初始值
  • 当一个隐藏动画后,高度值达到0的时候,display 样式属性被设置为none,以确保该元素不再影响页面布局
   $("button").click(function() {
            $("#a1").slideToggle(3000)
        });

7.jQuery中淡出动画fadeOut

设置元素透明度为0,可以让元素不可见,透明度的参数是0~1之间的值,通过改变这个值可以让元素有一个透明度的效果。常见的淡入淡出动画正是这样的原理。

fadeOut()函数用于隐藏所有匹配的元素,并带有淡出的过渡动画效果

所谓"淡出"隐藏的,元素是隐藏状态不对作任何改变,元素是可见的,则将其隐藏。

.fadeOut( [duration ], [ complete ] )

通过不透明度的变化来实现所有匹配元素的淡出效果,并在动画完成后可选地触发一个回调函数。这个动画只调整元素的不透明度,也就是说所有匹配的元素的高度和宽度不会发生变化。

字符串 'fast' 和 'slow' 分别代表200和600毫秒的延时。如果提供任何其他字符串,或者这个duration参数被省略,那么默认使用400毫秒的延时

 $("p").fadeOut();

 $("p").fadeOut({
                duration: 1000
            });
 $("p").fadeOut(2000, function() {
                alert("隐藏完毕!");
            });

8.jQuery中淡入动画fadeIn

fadeOut是淡出效果,相反的还有淡入效果fadeIn,方法使用上两者都是一致的,只是结果相反

.fadeIn( [duration ], [ complete ] )

  • duration:指定过渡动画运行多长时间(毫秒数),默认值为400。该参数也可以为字符串"fast"(=200)或"slow"(=600)。
  • 元素显示完毕后需要执行的函数。函数内的this指向当前DOM元素。

fadeIn()函数用于显示所有匹配的元素,并带有淡入的过渡动画效果。

注意:

  • 淡入的动画原理:操作元素的不透明度从0%逐渐增加到100%
  • 如果元素本身是可见的,不对其作任何改变。如果元素是隐藏的,则使其可见

9.jQuery中淡入淡出切换fadeToggle

fadeToggle()函数用于切换所有匹配的元素,并带有淡入/淡出的过渡动画效果。之前也学过toggle、slideToggle 也是类似的处理方式

fadeToggle切换fadeOut与fadeIn效果,所谓"切换",即如果元素当前是可见的,则将其隐藏(淡出);如果元素当前是隐藏的,则使其显示(淡入)。

常用语法:.fadeToggle( [duration ] ,[ complete ] )

可选的 duration 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。 可选的 callback 参数是 fadeToggle完成后所执行的函数名称。

fadeToggle() 方法可以在 fadeIn() 与 fadeOut() 方法之间进行切换。如果元素已淡出,则 fadeToggle() 会向元素添加淡入效果。如果元素已淡入,则 fadeToggle() 会向元素添加淡出效果。 (和上面的方式一样)

10.jQuery中淡入效果fadeTo

淡入淡出fadeIn与fadeOut都是修改元素样式的opacity属性,但是他们都有个共同的特点,变化的区间要么是0,要么是1

fadeIn:淡入效果,内容显示,opacity是0到1 fadeOut:淡出效果,内容隐藏,opacity是1到0

如果要让元素保持动画效果,执行opacity = 0.5的效果时,要如何处理?

如果不考虑CSS3,我们用JS实现的话,基本就是通过定时器,在设定的时间内一点点的修改opacity的值,最终为0.5,原理虽说简单,但是总不如一键设置这么舒服,jQuery提供了fadeTo方法,可以让改变透明度一步到位

语法

.fadeTo( duration, opacity ,callback)

必需的 duration参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。fadeTo() 方法中必需的 opacity 参数将淡入淡出效果设置为给定的不透明度(值介于 0 与 1 之间)。可选的 callback 参数是该函数完成后所执行的函数名称。

$("p").fadeTo("slow", 0.5);

$("p").fadeTo(1000, 0.2);
      
$("p").fadeTo(1000, 0.9, function() {
 alert('完成')
});

11.jQuery中toggle与slideToggle以及fadeToggle的比较

操作元素的显示和隐藏可以有几种方法。 例如:

  • 改变样式display为none
  • 设置位置高度为0
  • 设置透明度为0

都能达到这个目的,并且针对这样的处理jQuery都提供了各自的方法。show/hide、sildeDown/sildeUp、fadeIn/fadeOut。除此之外,还引入了toggle、sildeToggle以及fadeToggle切换方法

toggle、sildeToggle以及fadeToggle的区别:

  • toggle:切换显示与隐藏效果
  • sildeToggle:切换上下拉卷滚效果
  • fadeToggle:切换淡入淡出效果

当然细节上还是有更多的不同点:

toggle与slideToggle细节区别:

  • toggle:动态效果为从右至左。横向动作,toggle通过display来判断切换所有匹配元素的可见性
  • slideToggle:动态效果从下至上。竖向动作,slideToggle 通过高度变化来切换所有匹配元素的可见性

fadeToggle方法

  • fadeToggle() 方法在 fadeIn() 和 fadeOut() 方法之间切换。
  • 元素是淡出显示的,fadeToggle() 会使用淡入效果显示它们。
  • 元素是淡入显示的,fadeToggle() 会使用淡出效果显示它们。
  • 注释:隐藏的元素不会被完全显示(不再影响页面的布局)

12.jQuery中动画animate(上)

有些复杂的动画通过之前学到的几个动画函数是不能够实现,这时候就需要强大的animate方法了

操作一个元素执行3秒的淡入动画,对比一下2组动画设置的区别

语法:

.animate( properties ,[ duration ], [ easing ], [ complete ] )
.animate( properties, options )

.animate()方法允许我们在任意的数值的CSS属性上创建动画。2种语法使用,几乎差不多了,唯一必要的属性就是一组CSS属性键值对。这组属性和用于设置.css()方法的属性键值对类似,除了属性范围做了更多限制。第二个参数开始可以单独传递多个实参也可以合并成一个对象传递了

参数分解:properties:一个或多个css属性的键值对所构成的Object对象。要特别注意所有用于动画的属性必须是数字的,除非另有说明;这些属性如果不是数字的将不能使用基本的jQuery功能。比如常见的,border、margin、padding、width、height、font、left、top、right、bottom、wordSpacing等等这些都是能产生动画效果的。background-color很明显不可以,因为参数是red或者GBG这样的值,非常用插件,否则正常情况下是不能只用动画效果的。注意,CSS 样式使用 DOM 名称(比如 "fontSize")来设置,而非 CSS 名称(比如 "font-size")。

特别注意单位,属性值的单位像素(px),除非另有说明。单位em 和 %需要指定使用

.animate({
    left: 50,
    width: '50px' 
    opacity: 'show', 
    fontSize: "10em",
}, 500);

除了定义数值,每个属性能使用'show', 'hide', 和 'toggle'。这些快捷方式允许定制隐藏和显示动画用来控制元素的显示或隐藏

.animate({
    width: "toggle"
});

如果提供一个以+= 或 -=开始的值,那么目标值就是以这个属性的当前值加上或者减去给定的数字来计算的

.animate({
    left: '+=50px'
}, "slow");

duration时间

动画执行的时间,持续时间是以毫秒为单位的;值越大表示动画执行的越慢,不是越快。还可以提供'fast' 和 'slow'字符串,分别表示持续时间为200 和 600毫秒。

easing动画运动的算法

jQuery库中默认调用 swing。如果需要其他的动画算法,请查找相关的插件

complete回调

动画完成时执行的函数,这个可以保证当前动画确定完成后发会触发

 if (v == "1") {
            // 数值的单位默认是px
            $aaron.animate({
                width  :300,
                height :300
            });
        } else if (v == "2") {
            // 在现有高度的基础上增加100px
            $aaron.animate({
                 width  : "+=100px",
                 height : "+=100px"
            });
        } else if (v == "3") {
            $aaron.animate({
                fontSize: "5em"
            }, 2000, function() {
                alert("动画 fontSize执行完毕!");
            });
        } else if (v == "4") {
            //通过toggle参数切换高度
            $aaron.animate({
                width: "toggle"
            });
        }

13.jQuery中动画animate(下)

animate在执行动画中,如果需要观察动画的一些执行情况,或者在动画进行中的某一时刻进行一些其他处理,我们可以通过animate提供的第二种设置语法,传递一个对象参数,可以拿到动画执行状态一些通知

.animate( properties, options )

options参数

  • duration - 设置动画执行的时间
  • easing - 规定要使用的 easing 函数,过渡使用哪种缓动函数
  • step:规定每个动画的每一步完成之后要执行的函数
  • progress:每一次动画调用的时候会执行这个回调,就是一个进度的概念
  • complete:动画完成回调

其中最关键的一点就是:

如果多个元素执行动画,回调将在每个匹配的元素上执行一次,不是作为整个动画执行一次

列出常用的方式:

$('#elem').animate({
    width: 'toggle', 
    height: 'toggle'
  }, {
    duration: 5000,
    specialEasing: {
      width: 'linear',
      height: 'easeOutBounce'
    },
    complete: function() {
      $(this).after('<div>Animation complete.</div>');
    }
  });

14.jQuery中停止动画stop

动画在执行过程中是允许被暂停的,当一个元素调用.stop()方法,当前正在运行的动画(如果有的话)立即停止

语法:

.stop( [clearQueue ], [ jumpToEnd ] )
.stop( [queue ], [ clearQueue ] ,[ jumpToEnd ] )

stop还有几个可选的参数,简单来说可以这3种情况

  • .stop(); 停止当前动画,点击在暂停处继续开始
  • .stop(true); 如果同一元素调用多个动画方法,尚未被执行的动画被放置在元素的效果队列中。这些动画不会开始,直到第一个完成。当调用.stop()的时候,队列中的下一个动画立即开始。如果clearQueue参数提供true值,那么在队列中的动画其余被删除并永远不会运行
  • .stop(true,true); 当前动画将停止,但该元素上的 CSS 属性会被立刻修改成动画的目标值

简单的说:参考下面代码、

$("#aaron").animate({
    height: 300
}, 5000)
$("#aaron").animate({
    width: 300
}, 5000)
$("#aaron").animate({
    opacity: 0.6
}, 2000)
  • stop():只会停止第一个动画,第二个第三个继续
  • stop(true):停止第一个、第二个和第三个动画
  • stop(true ture):停止动画,直接跳到第一个动画的最终状态

15.jQuery中each方法的应用

jQuery中有个很重要的核心方法each,大部分jQuery方法在内部都会调用each,其主要的原因的就是jQuery的实例是一个元素合集

如下:找到所有的div,并且都设置样式,css只是一个方法,所以内部会调用each处理这个div的合集,给每个div都设置style属性

$('div').css(...)

jQuery的大部分方法都是针元素合集的操作,所以jQuery会提供$(selector).each()来遍历jQuery对象

.each只是处理jQuery对象的方法,jQuery还提供了一个通用的jQuery.each方法,用来处理对象和数组的遍历

语法

jQuery.each(array, callback )
jQuery.each( object, callback )

第一个参数传递的就是一个对象或者数组,第二个是回调函数

$.each(["Aaron", "慕课网"], function(index, value) {
  //index是索引,也就是数组的索引
  //value就是数组中的值了
});

each就是for循环方法的一个包装,内部就是通过for遍历数组与对象,通过回调函数返回内部迭代的一些参数,第一个参数是当前迭代成员在对象或数组中的索引值(从0开始计数),第二个参数是当前迭代成员(与this的引用相同

jQuery.each()函数还会根据每次调用函数callback的返回值来决定后续动作。如果返回值为false,则停止循环(相当于普通循环中的break);如果返回其他任何值,均表示继续执行下一个循环。

$.each(["Aaron", "慕课网"], function(index, value) {
    return false; //停止迭代
});

jQuery方法可以很方便的遍历一个数据,不需要考虑这个数据是对象还是数组

 // 遍历数组元素
            $.each(['Aaron', '慕课网'], function(i, item) {
                $aaron.append("索引=" + i + "; 元素=" + item);
            });

  $.each({
                name: "张三",
                age: 18
   }, function(property, value) {
                $aaron.append("属性名=" + property + "; 属性值=" + value);
   });

16.jQuery中查找数组中的索引inArray

在PHP有in_array()判断某个元素是否存在数组中,JavaScript却没有,但是jQuery封装了inArray()函数判断元素是否存在数组中。注意了:在ECMAScript5已经有数据的indexOf方法支持了,但是jQuery保持了版本向下兼容,所以封装了一个inArray方法

jQuery.inArray()函数用于在数组中搜索指定的值,并返回其索引值。如果数组中不存在该值,则返回 -1。

语法:

jQuery.inArray( value, array ,[ fromIndex ] )

用法非常简单,传递一个检测的目标值,然后传递原始的数组,可以通过fromIndex规定查找的起始值,默认数组是0开始

例如:在数组中查找值是5的索引

$.inArray(5,[1,2,3,4,5,6,7]) //返回对应的索引:4

注意:

如果要判断数组中是否存在指定值,你需要通过该函数的返回值不等于(或大于)-1来进行判断

 if (v == "1") {

            var index = $.inArray('Aaron',['test','Aaron', 'array','慕课网']);
     
            $aaron.text('Aaron的索引是: '+ index)
     
        } else if (v == "2") {
     
            //指定索引开始的位置
            var index = $.inArray('a',['a','b','c','d','a','c'],2);
     
            $aaron.text('a的索引是: '+ index)
        }

17.jQuery中去空格神器trim方法

页面中,通过input可以获取用户的输入值,例如常见的登录信息的提交处理。用户的输入不一定是标准的,输入一段密码:' 1123456 ",注意了: 密码的前后会留空,这可能是用户的无心的行为,但是密码确实又没错,针对这样的行为,开发者应该要判断输入值的前后是否有空白符、换行符、制表符这样明显的无意义的输入值。

jQuery.trim()函数用于去除字符串两端的空白字符

这个函数很简单,没有多余的参数用法

需要注意:

  • 移除字符串开始和结尾处的所有换行符,空格(包括连续的空格)和制表符(tab)
  • 如果这些空白字符在字符串中间时,它们将被保留,不会被移除

alert("值的长度:" + .trim(.trim(("#results2").val()).length)

18.jQuery中DOM元素的获取get方法

jQuery是一个合集对象,如果需要单独操作合集中的的某一个元素,可以通过.get()方法获取到

以下有3个a元素结构:

<a>1</a>
<a>2</a>
<a>3</a>

通过jQuery获取所有的a元素合集$("a"),如果想进一步在合集中找到第二2个dom元素单独处理,可以通过get方法

语法:

.get( [index ] )

注意2点

  • get方法是获取的dom对象,也就是通过document.getElementById获取的对象
  • get方法是从0开始索引

所以第二个a元素的查找: $(a).get(1)

负索引值参数

get方法还可以从后往前索引,传递一个负索引值,注意的负值的索引起始值是-1

同样是找到第二元素,可以传递 $(a).get(-2)

$aaron.get(1).style.color = "blue"
 $aaron.get(-1).style.color = "#8A2BE2"

19.jQuery中DOM元素的获取index方法

get方法是通过已知的索引在合集中找到对应的元素。如果反过来,已知元素如何在合集中找到对应的索引呢?

.index()方法,从匹配的元素中搜索给定元素的索引值,从0开始计数。

语法:参数接受一个jQuery或者dom对象作为查找的条件

.index() .index( selector ) .index( element )

  • 如果不传递任何参数给 .index() 方法,则返回值就是jQuery对象中第一个元素相对于它同辈元素的位置
  • 如果在一组元素上调用 .index() ,并且参数是一个DOM元素或jQuery对象, .index() 返回值就是传入的元素相对于原先集合的位置
  • 如果参数是一个选择器, .index() 返回值就是原先元素相对于选择器匹配元素的位置。如果找不到匹配的元素,则 .index() 返回 -1

简单来说:

<ul>
    <a></a>
    <li id="test1">1</li>
    <li id="test2">2</li>
    <li id="test3">3</li>
</ul>

$("li").index() 没有传递参数,反正的结果是1,它的意思是返回同辈的排列循序,第一个li之前有a元素,同辈元素是a开始为0,所以li的开始索引是1

如果要快速找到第二个li在列表中的索引,可以通过如下2种方式处理

$("li").index(document.getElementById("test2")) //结果:1
$("li").index($("#test2"))  //结果:1

571 jquery 动画 实例

图片切换 src

$(".TopImg").animate(
  {opacity:'toggle'},
  "slow",
  null,
  function(){
    $(".TopImg").attr("src","../images/2.jpg");
    $(".TopImg").animate({opacity:'toggle'},"slow");
  }
);

22.572 jquery 动画

jq 取消样式

$('#bottom_search_warp').css("height",'');

jq 动态设置 高度 为 auto

var el = $("#domId");
var curHeight = el.height();
var autoHeight = el.css('height', 'auto').height();
el.height(curHeight).stop().animate({height: autoHeight}, 500);

22.600 jQuery获取元素的宽度或高度的有几种情况:

1.使用width(),它只能获取当前元素的内容的宽度;

2.使用innerWidth(),它只能获取当前元素的内容的宽度+padding;

3.使用outerWidth(),它只能获取当前元素的内容的宽度+padding+border;

4,使用outerWidth(true),它只能获取当前元素的内容的宽度+padding+border+margin;

22.610 WdatePicker 日期插件

image-20210528092341738
image-20210528092341738
<div id="date" style="width:186px;height:176px;"></div>
<scripe>
WdatePicker({
    eCont:'date',
    startDate:'${device.rtime}',
    onpicked:function(dp){
        $("#rtime").val(dp.cal.getDateStr());
        window.location.replace("${ctx}/trans/trans/transPictureOnlyNew?equipid=${equipid}&rtime="+dp.cal.getDateStr());
    }
})
 </scripe>

22.620回车

 <input id="search-from-input" class="search-input" type="text" onkeydown="keyDownMenuSeach(event);" placeholder="请输入关键字..." autocomplete="off" >
                    <div id="search-from-button" class="search-input-button div_button" onclick="menuSeach();">查询</div>
 // $('#search-from-input').bind('keypress', function (event) {
        //     if (event.keyCode == "13") {
        //         $("#search-from-button").click();
        //     }
        // })
        //回车触发搜素,搜素
        function keyDownSeach(e) {
            // 兼容FF和IE和Opera
            var theEvent = e || window.e;
            var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
            if (code == 13) {
                $("#search-from-button").click();
            }
        }

22.630 js 格式化时间

new Date(item.warnTime).format("yyyy-MM-dd hh:mm:ss")

前端处理 后端方回的list集合

var listJson=${fns:toJson(list)};

22.640 自定义时钟

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<script type="text/javascript">
    function getnow(){
          //1、获得当前时间,格式化时间
  			var show_day=new Array('星期一','星期二','星期三','星期四','星期五','星期六','星期日'); 
           var now=new Date(); 
           var year=now.getFullYear(); 
           var month=now.getMonth()+1;
           if(month<10){
              month="0"+month;
           }  
           var date=now.getDate();
           if(date<10){
              date="0"+date;
           }
          var hour=now.getHours();
           if(hour<10){
              hour="0"+hour;
           }
          var minute=now.getMinutes();
           if(minute<10){
              minute="0"+minute;
           } 
           var second=now.getSeconds();
            if(second<10){
              second="0"+second;
           }
           var nowstr=year+"."+month+"."+date+" "+show_day[(new Date().getDay())-1]+" "+hour+":"+minute+":"+second;
           //alert(nowstr);
           //2、显示时间 html
           //获得标签对象
           var nowspan=document.getElementById("nowspan");
           nowspan.innerHTML=nowstr;
           //3、使时间动起来
           setTimeout("getnow()", 1000);
}
</script>
<body onLoad="getnow()">
<span id="nowspan" />
</body>
</html>

22.650引入 第三方js (js缓存)

window.onLoad  = function(){
          //
}
var url = 'https://webapi.amap.com/maps?v=1.4.15&key=8d1f0b086583b79a9ddbd6040c6af3e3&callback=onLoad';
var jsapi = document.createElement('script');
jsapi.charset = 'utf-8';
jsapi.src = url;
document.head.appendChild(jsapi);

22.660 回调& 异步回调

方式1

if (typeof callback === 'function') {
	callback(true);
}
$rootScope.getPosition = function(successCallback){
	function failedCallback(message){
		message = jQuery.parseJSON(message);
		$ionicPopup.alert({
			title: '实时定位',
			template: message.describe,
			okText:'确定'
		});
	}
	$rootScope.http({
			 method:'get',
			 url:'/Location/getPosition',
			 headers: {
				 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				 'Accept': '*/*'
			 },
			 params:{lontitude:position.coords.longitude,latitude:position.coords.latitude}
		 },function(response){
			 if(response.status=="0"){
					successCallback(response.t);
			 }else{
				 failedCallback();
			 }
		 })
}

// 调用
$rootScope.getCurrentPosition=function(item){
    function successCallback(position){
        initMap(position.lontitude,position.latitude);
    }
    $rootScope.getPosition(successCallback);
}

方式2

https://blog.csdn.net/qq_41702660/article/details/84890453open in new window

/** 请注意 这个代码是结合 阮老师 的博客来实现的.
 * 网址 http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html
 * 如果有不懂的请看 阮老师 的网址
 */
 
// JQ 1.5 版本之前的 AJAX 方法
/**
 * success : 这是一个成功的回调函数
 * error : 这是一个失败的回调函数
 */
$.ajax({
    type: "get",
    url: "./test1.json",
    data: "",
    dataType: "json",
    success: function(response) {
        console.log(response);
    },
    error: function(err) {
        console.log(err);
    }
});
 
// JQ 1.5 版本之后的 AJAX 方法
/**
 * done : 这是一个成功的回调函数
 * fail : 这是一个失败的回调函数
 */
// (写法1)
$.ajax('./test1.json').done(function() {
    console.log('成功了 ');
}).fail(function() {
    console.log('失败了');
})
 
/**
 * then : then 接受两个参数, 一个是成功的回调函数, 一个是失败的回调函数
 *        如果成功了,会调用第一个回调函数, 如果失败了, 会调用第二个回调函数
 */
// (写法2)
$.ajax('./test1.json').then(function() {
    console.log('成功了');
}, function() {
    console.log('失败了');
})
 
/** 
 * ------------------------------------------------ $.when() ------------------------------------------------------
 * (引入 $.when() )
 * 提供一种方法来执行零个或多个( Thenable \ then \ Deferred ) 对象的回调函数,通常是表示异步事件
 * 如果没有参数传递给 jQuery.when(),它会返回一个resolved状态的Promise。
 * 切记 : 如果传参数 那么 他将永远返回的是 成功 的状态, 失败定义的回调函数, 永远不会被执行, 因为不会遭到拒绝
 * 如果传参是 不是一个 Deferred 或 Promise 对象, 那么他将永远返回的是 成功 的状态, 失败定义的回调函数, 永远不会被执行, 因为不会遭到拒绝
 * 
 * 上面说的两种 都不是 异步对象, 所以会直接返回 成功时的回调
 * 如果说是成功的回调, 我们需要调用方法, done 和 fail 只是定义方法, 并没有调用, 不调用 并不会执行!!!
 * resolve() : 这是调用成功的回调, 也就是说 定义的 done 的回调
 * reject() : 这是调用失败的回调, 也就是说 定义的 fail 的回调
 * 如果定义了 两个回调, 并且也执行了 resolve 和 reject, 只会执行最先执行的方法.
 * 如果定义了 成功的 回调, 却执行了 reject 方法, 那么并不会执行,  因为你没有定义方法
 */
 
$.when().done(function() {
    console.log('成功了'); /** 成功了 */
}).fail(function() {
    console.log('失败了');
})
 
$.when({ testing: 123 }).done(
    function(x) { alert(x.testing); } /* alerts "123" */
);
 
var dtd = $.Deferred()
$.when(dtd).done(function() {
    console.log('1111');
}).fail(function() {
    console.log('2222');
})
dtd.resolve() // 111
dtd.reject() // 不会执行,因为并没有定义失败的回调
 
/**
 * $.when(参数1, 参数2, 参数3...)
 * 此方法接受多个参数, 但是返回的结果却是不一样的, 但是无非还是两种状态, 一种成功时的状态, 一种失败时的状态
 * 成功时的状态 : 必须所有的对象都返回成功, 才会返回成功的回调函数
 * 失败时的状态 : 如果其中只要有一个返回失败, 都会返回失败的回调函数
 * 如果定义函数的时候给了参数, 调用函数的时候没给参数, 那么值将会是 undefined
 */
 
/** d1, d2 时定义了两个 异步 对象 */
var d1 = $.Deferred();
var d2 = $.Deferred();
/** 调用 when 方法, 并且设置 ( 此处只是设置或者说定义, 并不是调用 ) 成功的回调*/
$.when().done(function(v1, v2) {
    console.log(v1); // "Fish"
    console.log(v2); // "Pizza"
});
/** 调用成功时的方法 */
// d1.resolve("Fish");
// d2.resolve("Pizza");
 
var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();
var d4 = $.Deferred();
var d5 = $.Deferred();
/** 调用 when 方法, 并且设置 ( 此处只是设置或者说定义, 并不是调用 ) 成功的回调*/
$.when(d1, d2, d3, d4, d5).done(function(v1, v2, v3, v4, v5) {
    console.log(v1); // "Fish"
    console.log(v2); // "Pizza"
    console.log(v3); // undefined
    console.log(v4); // is Array  [1, 2, 3]
    console.log(v5); // is Object {a: "a"}
});
/** 调用成功时的方法 */
d1.resolve("Fish");
d2.resolve("Pizza");
d3.resolve();
d4.resolve(1, 2, 3);
d5.resolve({ a: "a" });
 
 
var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();
 
$.when(d1, d2, d3).done(function(v1, v2, v3) {
    console.log(v1); // v1 is undefined
    console.log(v2); // v2 is "abc"
    console.log(v3); // v3 is an array [ 1, 2, 3, 4, 5 ]
});
 
d1.resolve();
d2.resolve("abc");
d3.resolve(1, 2, 3, 4, 5);

js回调函数callback传值与取值

https://blog.csdn.net/XTXTXTXTYYYY/article/details/100040229open in new window

1.简单的回调

function demo(callback){
    callback(1)
}
demo(function(e) {
    console.log(e)  //1
})
  1. 回调取值
function demo(callback){
    var opts = {
        ids: [1,2,3,4],
        list: ['ho','yang','lee','chan']
    }
    callback(opts)
};
demo(function(e) {
    console.log(e) //{"ids":[1,2,3,4],"list":["ho","yang","lee","chan"]}
})
  1. 回调传值与取值
function demo(originalOpts,callback){
    var opts = {
        ids: originalOpts.ids.concat([5,6,7]),
        list: originalOpts.list.concat(['xu','zhu','fu'])
    }
    callback(opts)
}
demo({
	ids: [1,2,3,4],
	list: ['ho','yang','lee','chan']
	},function(e) {
    console.log(e)  //{"ids":[1,2,3,4,5,6,7],"list":["ho","yang","lee","chan","xu","zhu","fu"]}
})

冒泡

  • js
<input  onclick="popupCheck2(event)">

function popupCheck2(e){
    e.preventDefault();
}
  • angularJs
event.stopPropagation();
event.preventDefault();

监听浏览器窗口大小改变

//js
window.addEventListener('resize', () => { //监听浏览器窗口大小改变
     //浏览器变化执行动作
});

// jq
window.onresize = function(){
	//浏览器变化执行动作
}

22.665 绑定事件

layer.on('touchstart', function (e) {
     checkMarker(e.target)
});


layer.on('touchstart', checkMarker);

Jquery删除css属性

$('选择器').css('css属性',''); 

22.675 js中hex16进制颜色与rgb互转

// hex 转 rgb (#fff--->rgb(255, 255, 255))
function hexToRgba(hex, opacity) {
    return "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt("0x" + hex.slice(5, 7)) + "," + opacity + ")";
}


function rgbToHex(r, g, b) {
    return ((r << 16) | (g << 8) | b).toString(16);
}

23.680 图片预加载

https://blog.csdn.net/u011215669/article/details/80526530open in new window

http://www.createjs.cc/preloadjs/docs/classes/LoadQueue.htmlopen in new window

preloadjs.js

//    <script src="preloadjs.js" type="text/javascript"></script><%-- 预加载--%>
//<script src="jquery.min.js"></script>
var loadManifestList=[];
                    // 预加载下一页图片
                    $.each(data.list,function(index,item){
                        loadManifestList.push(item.filepathSmall)
                    });

                    console.log("开始加载....."+ JSON.stringify(loadManifestList))
                    //使用preload.js
                    var queue=new createjs.LoadQueue(false);//默认是xhr对象,如果是new createjs.LoadQueue(false)是指使用HTML标签,可以跨域
                    queue.on("complete",handleComplete,this);
                    queue.loadManifest(loadManifestList);
                    function handleComplete(){
                        console.log("当前第"+wheelPlayItemTemp.pageNo+"页预加载完成.....")
                    }

给元素addClass并绑定点击事件,点击事件不生效的解决办法

  • 初始代码--未实现效果(绑定的close 的事件无法生效,主要是dom没有重新加载)
<body>
    <div class="open">展开</div>
    <script>
        $(".open").click(function () {//展开
            console.log("open----");
            $(this).removeClass("open").addClass("close");
            $(this).html("收起");
        })
        $(".close").click(function () {//收起
            console.log("close----");
            $(this).removeClass("close").addClass("open");
            $(this).html("展开");
        })
    </script>
</body>
  • 解决方法1
<script>
    $(document).on("click", ".open", function () {
        console.log("open----");
        $(this).removeClass("open").addClass("close");
        $(this).html("收起");
    })
    $(document).on("click", ".close", function () {
        console.log("close----");
        $(this).removeClass("close").addClass("open");
        $(this).html("展开");
    })
</script>
  • 解决方法2
<body>
    <div class="operate open">展开</div>
    <script>
        $(".operate").click(function () {
            if ($(this).hasClass("open")) {//展开
                console.log("open----");
                $(this).removeClass("open");
                $(this).html("收起");
            } else {//收起
                console.log("close----");
                $(this).addClass("open");
                $(this).html("展开");
            }
        })
    </script>
</body>

layer.photos放大缩小以及旋转

22.690 JS判断单、多张图片是否加载完成

https://blog.csdn.net/sinat_35656188/article/details/102464292open in new window

一、单张图片(图片在文档中)
// HTML
<img id='xiu' src="/images/logo.png">  

//js
 $(document).ready(function(){

    //jquery
    $('#xiu').load(function(){
       // 加载完成 
    });

   //原生  onload
    var xiu = document.getElementById('xiu')
    xiu.onload = xiu.onreadystatechange = function(){
       if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){
           // 加载完成 
       }
    };

})
1234567891011121314151617181920

注: 1、IE8及以下版本不支持onload事件,但支持onreadystatechange事件; 2、readyState是onreadystatechange事件的一个状态,值为loaded或complete的时候,表示已经加载完毕。 3、以下内容省略兼容

二、单张图片(图片动态生成)
//js
 var xiu = new Image()
 xiu.src = '/images/logo.png'
 xiu.onload = function(){
    // 加载完成 
 }
123456
三、单张图片(结合ES6 Promise)
//js
 new Promise((resolve, reject)=>{
    let xiu = new Image()
    xiu.src = '/images/logo.png'
    xiu.onload = function(){
       // 加载完成 
       resolve(xiu)
    }
 }).then((xiu)=>{
 //code
 })
1234567891011
四、多张图片
var img = [],  
    flag = 0, 
	mulitImg = [
	   '/images/logo.png',
	   '/images/logo.png',
	   '/images/logo.png',
	   '/images/logo.png'
 ];
 var imgTotal = mulitImg.length;
 for(var i = 0 ; i < imgTotal ; i++){
    img[i] = new Image()
    img[i].src = mulitImg[i]
    img[i].onload = function(){
       //第i张图片加载完成
       flag++
       if( flag == imgTotal ){
          //全部加载完成
       }
    }
 }
1234567891011121314151617181920
五、多张图片(结合ES6 Promise.all())
 let mulitImg = [
  '/images/logo.png',
   '/images/logo.png',
   '/images/logo.png',
   '/images/logo.png'
 ];
 let promiseAll = [], img = [], imgTotal = mulitImg.length;
 for(let i = 0 ; i < imgTotal ; i++){
     promiseAll[i] = new Promise((resolve, reject)=>{
         img[i] = new Image()
         img[i].src = mulitImg[i]
         img[i].onload = function(){
              //第i张加载完成
              resolve(img[i])
         }
     })
 }
 Promise.all(promiseAll).then((img)=>{
     //全部加载完成
 })
案例

场景:集控中心 有个轮播功能,设置定时器时间,到点自定加载下一页,但是由于网络的问题,导致查询数据和图片加载需要很长时间,所以导致,可能出现了,当前页还没加载完成,就自定轮播下一页了。故现在需要 监听当前页面图片全部加载完成后 在给执行 轮播下一页


        var startWheelPlayFlag=false;// 轮播 启动标识 默认是 暂停
        var autoWheelPlaytimer;// 轮播定时器
// 轮播定时器
        function autoWheelPlay() {
            if(!startWheelPlayFlag){
                return;
            }
            stopWheelPlay();// 防止多次调用 定时器
            var last_auto_wheel_playtimer = (new Date()).getTime();
            autoWheelPlaytimer = setInterval(function () {
                //console.log("轮播"+wheelPlayItem.playTime);
                var current_auto_wheel_playtimer = (new Date()).getTime();
                console.log("轮播用时:"+(current_auto_wheel_playtimer-last_auto_wheel_playtimer)/1000+'s');
                last_auto_wheel_playtimer=current_auto_wheel_playtimer;
                if(!initDataFinishFlag){
                    console.log("当前页数据还未加载完成,不执行加载下一页!")
                    return;
                }
                nextPage();
            }, wheelPlayItem.playTime*1000);
        }



 var currentPageImgMap={};// 记录当前页 中 图片 ,用于 验证当前页 图片是否加载完成,--轮播是用到
/* 图片排版*/
        function arrangePic(data) {
           jQuery.each(data, function (index, item) {
                // 记录当前页 中 图片 ,用于后面的监听 图片加载完成
                if(currentPageImgMap[wheelPlayItem.pageNo]==undefined){
                    currentPageImgMap[wheelPlayItem.pageNo]=[];
                }
                if(item.filepathSmall!=null && item.filepathSmall!=''){
                    currentPageImgMap[wheelPlayItem.pageNo].push(item.filepathSmall);
                }
            });
            // 图片加载到页面
            //代码省略
            
            currentPageImgLoadListening(currentPageImgMap);// 当前页图片是否加载完成 监听,用于改写 initDataFinishFlag 状态(轮播是用到)
        }



 /**
         * 当前页图片是否加载完成 监听,用于改写 initDataFinishFlag 状态(轮播是用到)
         */
        function currentPageImgLoadListening(imgMap) {
            console.log("开始监听图片是否加载完成!");
            var mulitImg = imgMap[wheelPlayItem.pageNo];
            function callback(result) {
                // 图片加载完成
                initDataFinishFlag=true;
                // 缓存 下一页的 图片,用来加快 页面图片加载 速度
                getNextData();
            }
            currentPageImgLoad(mulitImg,callback);
        }
        function currentPageImgLoad(mulitImg,callback) {
            var img = [],flag = 0;
            var imgTotal = mulitImg.length;
            for(var i = 0 ; i < imgTotal ; i++){
                img[i] = new Image();
                img[i].src = mulitImg[i];
                img[i].onload = function(){
                    //第i张图片加载完成
                    flag++;
                    if( flag == imgTotal ){
                        //全部加载完成
                        console.log("全部加载完成");
                        callback(true);
                    }
                };
                // 图片失败,也算加载完成
                img[i].onerror=function(){
                    flag++;
                    if( flag == imgTotal ){
                        //全部加载完成
                        console.log("全部加载完成");
                        callback(true);
                    }
                };
            }
        }

23.680 Web页面的数据导出excel时的格式问题(长数字显示为科学计数法格式等)

1) 文本:vnd.ms-excel.numberformat:@

2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd

3) 数字:vnd.ms-excel.numberformat:#,##0.00

4) 货币:vnd.ms-excel.numberformat:¥#,##0.00

5) 百分比:vnd.ms-excel.numberformat: #0.00%

<td style="vnd.ms-excel.numberformat:@">410522198402161833</td>


<table style=’vnd.ms-excel.numberformat:#,##0.00’>
    <tr>
        <td>542</td>
        <td style=’vnd.ms-excel.numberformat: #0.00%’>0.25</td>
    </tr>
</table>

23.700 时间轴

1.水平放心时间轴

<style>
.tr_line{
      width: 100%;
      height: 1px;
      background: #F5F5F5;
  }

  /*时间轴*/
  .time-box ul {
      overflow: hidden;
      position: relative;
      height: 100%;
  }

  /*时间轴*/
  .time-box ul:after {
      content: "";
      background: #d2d2d2;
      height: 1px;
      width: 100%;
      position: absolute;
      left: 0;
      top: 50%;
  }
  .time-box li {
      float: left;
      padding: 0 10px;
      box-sizing: border-box;
      position: relative;
      cursor: pointer;
      height: 100%;
      min-width: 50px;
      list-style: none;
  }
  .time-box li:nth-child(1) p, .time-box li:nth-last-child(1) p {
      position: absolute;
      top: 70%;
      bottom: 0;
  }
    /*使用 iconfont 作为轴心图标*/
  .time-box li:after {
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      font-family: "iconfontQs" !important;
      content: "\e703";
      z-index: 1;
      font-size: 30px;
      font-style: normal;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
  }
  /**.time-box li:after {
      content: "";
      background: url(img/point.png) no-repeat;
      z-index: 1;
      font-size: 30px;
      font-style: normal;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
  }*/
</style>
<div class="mb10 time-box" style="height: 80px;width: 100%;"><!--YJ站 时间轴 展示-->
    <ul class="wh100">
        <li><p>12</p></li>
        <li><p>13</p></li>
        <li><p>14</p></li>
        <li><p>15</p></li>
    </ul>
</div>

23.690 在线绘图插件--wPaint 的实际应用

https://blog.csdn.net/monkeyking1987/article/details/9100977open in new window

wPaint 网址: http://wpaint.websanova.com/#websanovaopen in new window

1.在HTML页面上定义一个wPaint的容器.

<div id="wPaint"></div>

最好对容器设置样式.

 #wPaint {
            position: relative;
            width: 680px;
            height: 600px;
            background: #CACACA;
            border: solid black 1px;
            margin-bottom: 10px;
            margin-top: 10px;
            margin-left: 5px;
            float: left;
        }css

引入JS,CSS.

<!-- wColorPicker -->
<link rel="Stylesheet" type="text/css" href="/js/jquery/wPaint/inc/wColorPicker.css"/>
<script type="text/javascript" src="/js/jquery/wPaint/inc/wColorPicker.js"></script>
 
<!-- wPaint -->
<link rel="Stylesheet" type="text/css" href="/js/jquery/wPaint/wPaint.css"/>
<script type="text/javascript" src="/js/jquery/wPaint/wPaint.js"></script>

2. 初始化wPaint.JS代码

 $('#wPaint').wPaint({
        fillStyle: "#ffffff",
        image:"${dataDto.base64Image}",//  base64格式的图片数据 如果不需要背景图片,则不需要设置
        strokeStyle: "#333333"
    });

wPaint 下的 image 是绘图容器的背景图片数据(png格式), base64格式的图片数据.

${dataDto.base64Image}
# 对应 base64格式如下
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAGQCAYAAABY...

如果不需要背景,则不需要设置.

3. 对应需要背景图片作为底图的2种获取方式

  • 在JAVA中,我们可以使用 BASE64Encoder类来转化.
public static String imageToBase64(byte[] imageBytes) {
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(imageBytes);
}
  • 前端

h5图片转base64

<!Doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>html5 image to base64</title>
    </head>
    <body>
        <script type="text/javascript">
			var img = "https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";
			function getBase64Image(img) {
				var canvas = document.createElement("canvas");
				canvas.width = img.width;
				canvas.height = img.height;

				var ctx = canvas.getContext("2d");
				ctx.drawImage(img, 0, 0, img.width, img.height);
				var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
				var dataURL = canvas.toDataURL("image/"+ext);
				return dataURL;
			}
			var image = new Image();
				image.crossOrigin = '';
				image.src = img;
				image.onload = function(){
				var base64 = getBase64Image(image);
				console.log(base64);
			}
        </script>
        
    </body>
</html>

4. 在绘制图片完成后, 需要保存绘制的图片.

4.1 获取wPaint的image属性值可获取base64格式的图片数据
var imageData = $("#wPaint").wPaint("image");
4.2 在JAVA后台可使用BASE64Decoder 类将base64数据转化为byte数组.
public static byte[] base64ToBytes(String bast64Str) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] bytes = decoder.decodeBuffer(bast64Str);
            //调整异常数据
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;java
                }
            }
            return bytes;
        } catch (IOException e) {
            throw new IllegalStateException("Convert base64 data error", e);
        }
    }

使用jQuery控制页面滚动条上下滚动

//
$("xxx").animate({ scrollTop: "+=50" }, 1000);// 父容器,内部的元素向下 滚动50px
 
 
 // 父容器使用的是绝对定位,通过设置 top等属性来控制位移
$(function () {
    $(window).scroll(function () {
        var top = $(window).scrollTop() + 200;
        var left = $(window).scrollLeft() + 320;
        //$("#editInfo").animate({ "top": top }, 30);  //方式一 
        $("#editInfo").css({ left: left + "px", top: top + "px" });  方式二 
    });
}); 

焦点&光标

验证文档是否失去焦点

// 正对的是 document,当前页
function myFunction() {
    var x = document.getElementById("demo");
    if (document.hasFocus()) {
        x.innerHTML = "文档已获取焦点。";
    } else {
        x.innerHTML = "文档失去焦点。";
    }
}

验证指定 输入框是否失去焦点

$("#myinp").click(function(){
    if(document.activeElement.id==="myinp" ){// myinp元素id属性值
        alert("获取焦点了");
    }else{
        alert("没有获取焦点");
    }
});

案例:

$(document).ready(function() {
		/// 输入框 获取光标 移除提示
        $("input").on("focus",function(){
            getFocus();
        });
	});

    /* 获取光标,移除 提示*/
    var getFocus=function(){
        $("#messageBox").addClass("hide");
        $("#messageBox").css("display","none");
    }

23.700 密码校验

https://www.cnblogs.com/willingtolove/p/10976328.htmlopen in new window

#场景一:密码中必须包含大小写 字母、数字、特称字符,至少8个字符,最多30个字符;

var pwdRegex = new RegExp('(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{8,30}');
 
if (!pwdRegex.test('A3b@C2dEF')) {
  alert("您的密码复杂度太低(密码中必须包含大小写字母、数字、特殊字符),请及时修改密码!");
}

#场景二:密码中必须包含字母(不区分大小写)、数字、特称字符,至少8个字符,最多30个字符;

var pwdRegex = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}');
if (!pwdRegex.test('a2b3c$def')) {
    alert("您的密码复杂度太低(密码中必须包含字母、数字、特殊字符),请及时修改密码!");
}

场景三:密码中必须包含字母(不区分大小写)、数字,至少8个字符,最多30个字符;

var pwdRegex = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z]).{8,30}');
if (!pwdRegex.test('a2b3c4d5')) {
    alert("您的密码复杂度太低(密码中必须包含字母、数字),请及时修改密码!");
}

开关


22.800 获取元素的位置

let elem = document.getElementById('playWnd');
let rect = elem.getBoundingClientRect();
console.log(rect);
/*
    bottom: 828.984375
    height: 236.84375
    left: 15.53125
    right: 517.984375
    top: 592.140625
    width: 502.453125
    x: 15.53125
    y: 592.140625
*/

22.810 获取元素的左右,上下位置

var dom = this.$refs[`item_li_${this.menuImgIndexActive}`]
var left = dom.getBoundingClientRect();// getBoundingClientRect 方法,针对的时 dom 元素

22.830 开关

this.pop_video_need_click=false;//开关,防止 视频 下一页上一页 会有冒泡问题
                this.pop_video_need_click_timer = setTimeout(()=>{   //设置延迟执行
                    this.pop_video_need_click=true;
                    clearTimeout(this.pop_video_need_click_timer);  //清除延迟执行
                },300);

22.840 前端构造树结构/递归

https://www.cnblogs.com/tugenhua0707/p/15948251.htmlopen in new window

	/**
	 * 组装树结构
	 * 考虑该功能可能需要离线使用,所以将数据获取到,通过js递归的形式,来组装数据
	 */
	var getTree=function(treeData,parentId){
	       var treeArr=[];
	       for(var i=0;i<treeData.length;i++){ 
	           var node=treeData[i];
	            if(node.parentId==parentId ){ 
	               var newNode={
	            		   id:node.id,
	            		   name:node.name,
	            		   parentId:node.parentId,
	            		   type:node.type,
	            		   nodeType:node.nodeType,
	            		   children:getTree(treeData,node.id)
	               };
	               treeArr.push(newNode);              
	            }
	       }
	       return treeArr;
	 }
    
    
    
    
  /**
 *  构造树结构 ---- 通过 rid 进行 筛选,这样有个问题,如果 有些数据没有父节点,或者父节点找不到了数据就不会显示了
  * @param data
 * @param id
 * @param parentId
 * @param children
 * @param rid
 * @returns {[]}
 */
export function buildTree(data, rid, parentId = 'parentId', id = 'id', children = 'children') {
  const tree = [];

  function buildNode(pid) {
    const nodes = [];
    for (const item of data) {
      if (item[parentId] === pid || item[id] === rid) {
        const nodeId = item[id];
        const node = { ...item };
        const childNodes = buildNode(nodeId);
        if (childNodes.length > 0) {
          node[children] = childNodes;
        }
        nodes.push(node);
      }
    }
    return nodes;
  }
  tree.push(...buildNode(rid));
  return tree;
}



/**
 *  构造树结构
  * @param data
 * @param id
 * @param parentId
 * @param children
 * @param rid
 * @returns {[]}
 */
export function buildTree(data, parentId = 'parentId', id = 'id', children = 'children') {
  const map = {};
  const tree = [];

  // 构建哈希表
  for (const item of data) {
    const nodeId = item[id];
    map[nodeId] = { ...item, [children]: [] };
  }

  // 构建树结构
  for (const item of data) {
    const nodeId = item[id];
    const parentNodeId = item[parentId];
    const node = map[nodeId];
    if (parentNodeId) {
      const parentNode = map[parentNodeId];
      parentNode[children].push(node);
    } else {
      tree.push(node);
    }
  }

  return tree;
}




js时间处理

js 获取昨天,今天,本周,上周,季度等时间范围:http://t.zoukankan.com/Duriyya-p-10536680.htmlopen in new window

昨天:new Date(new Date().setDate(new Date().getDate() - 1))

var day = new Date();

var today = day.format('yyyy-MM-dd');//今天
var yesterday = new Date(new Date().setDate(new Date().getDate() - 1)).format('yyyy-MM-dd');//昨天

//本月第一天和本月最后一天
var thismonth1 = new Date(new Date().setDate(1)).format('yyyy-MM-dd');
var thismonth2 = new Date(new Date(new Date().setMonth(new Date().getMonth() + 1)).setDate(0)).format('yyyy-MM-dd');
//上一月第一天和最后一天          
var lastmonth1 = new Date(new Date(new Date().setMonth(new Date().getMonth() - 1)).setDate(1)).format('yyyy-MM-dd');
var lastmonth2 = new Date(new Date().setDate(0)).format('yyyy-MM-dd');

//本周的第一天和最后一天
var weekday = new Date().getDay() || 7;
var thisweek1 = new Date(new Date().setDate(new Date().getDate() - weekday + 1)).format('yyyy-MM-dd');
var thisweek2 = new Date(new Date().setDate(new Date().getDate() - weekday + 7)).format('yyyy-MM-dd')

//上周的第一天和最后一天
var lastweek1 = new Date(new Date().setDate(new Date().getDate() - weekday - 6)).format('yyyy-MM-dd');
var lastweek2 = new Date(new Date().setDate(new Date().getDate() - weekday)).format('yyyy-MM-dd')

//本季度第一天和最后一天
var month = new Date().getMonth();
var newmonth
var newmonth1
if (month < 3) {
    newmonth = new Date(new Date().setMonth(0))
    newmonth1 = new Date(new Date().setMonth(3))
} else if (2 < month && month < 6) {
    newmonth = new Date(new Date().setMonth(3))
    newmonth1 = new Date(new Date().setMonth(6))
} else if (5 < month && month < 9) {
    newmonth = new Date(new Date().setMonth(6))
    newmonth1 = new Date(new Date().setMonth(9))
} else if (8 < month && month < 11) {
    newmonth = new Date(new Date().setMonth(9))
    newmonth1 = new Date(new Date().setMonth(12))
}
var thisseason1 = new Date(newmonth.setDate(1)).format('yyyy-MM-dd')
var thisseason2 = new Date(newmonth1.setDate(0)).format('yyyy-MM-dd')
//上半年第一天和最后一天
var firsthalf1 = new Date(new Date(new Date().setMonth(0)).setDate(1)).format('yyyy-MM-dd')
var firsthalf2 = new Date(new Date(new Date().setMonth(6)).setDate(0)).format('yyyy-MM-dd')

//下半年第一天和最后一天
var secondehalf1 = new Date(new Date(new Date().setMonth(6)).setDate(1)).format('yyyy-MM-dd')
var secondehalf2 = new Date(new Date(new Date().setMonth(12)).setDate(0)).format('yyyy-MM-dd')
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) 
        if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
        RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}

每隔3个

// 防止只显示GT编号,会不容易区分,故 每隔3个 显示完整名称
if (index % 4 == 3) {
	XXXXX
}

循环删除

如果直接使用forEach会存在异常

var arr = [1,2,2,3,4,5];
var i = arr.length;
while(i--){
   arr.splice(i,1);
}
console.log(arr);

计算周次

export const getCurrentWeekNum = (currentDate = new Date()) => {
	const firstDayOfWeek = new Date(currentDate.getFullYear(),0,1); // 所在年的第一天
	    // 设置时间部分为 0,即凌晨 0 点
    firstDayOfWeek.setUTCHours(0, 0, 0, 0);

	  // 获取本年第一天是星期几
	const dayOfWeek = firstDayOfWeek.getDay();
	// 将第一天调整为所在周的第一天
	firstDayOfWeek.setDate(firstDayOfWeek.getDate() - dayOfWeek + 1);

	// 计算当前日期与年初第一个周一的时间差(毫秒数)
	var timeDiff = Math.abs(currentDate.getTime() - firstDayOfWeek.getTime());
	var diffDays = Math.floor(timeDiff / (24 * 60 * 60 * 1000))+1;
	// 将时间差转换为周数
	return Math.ceil(diffDays /7);
}

循环取余

  // 使用取余来确保循环色板,动态根据 colorArr 的长度
item.color = this.colorArr[index % this.colorArr.length];

23 ztree

23.1 ztree 如果想输出html 格式的name

view: {
            expand:true,
            dblClickExpand: false,
            showLine: true,
            nameIsHTML:true// 表示 输出 html 
        }

23.2 title

相优先用title 然后 在用name 作为title 属性

/*ztree.js
getNodeTitle 方法
*/

getNodeTitle: function(setting, node) {
			if(node[setting.data.key.title]!=undefined && node[setting.data.key.title]!=""){
				return "" + node[setting.data.key.title];
			}else{
				return "" + node[setting.data.key.name];
			}
			//var t = setting.data.key.title === "" ? setting.data.key.name : setting.data.key.title;
			//return "" + node[t];
		},

23.10 勾选 checkbox 对于父子节点的关联关系

勾选 checkbox 对于父子节点的关联关系。[setting.check.enable = true 时生效]

默认值:{ "Y": "ps", "N": "ps" } 表示 勾选父节点 或者取消父节点 选中或取消

说明:

Y 属性定义 checkbox 被勾选后的情况; N 属性定义 checkbox 取消勾选后的情况; "p" 表示操作会影响父级节点; "s" 表示操作会影响子级节点。

请注意大小写,不要改变

  • 勾选父节点 子节点不联动
var setting = {
	check: {
		enable: true,
		chkStyle: "checkbox",
		chkboxType: { "Y": "p", "N": "ps" }
	}
};

60 layui

layer.open 关闭回调

https://www.cnblogs.com/-hao/p/9202638.htmlopen in new window


layer.open({
    title: '详细信息',
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['70%', '78%'], //宽高
    content: $('#freightDirectiontb'),//dom标签
    success:function(layero, index){
        //
    },
    end: function(){
        // 关闭弹窗的回调
    }
});

65 AngularJs

动画

http://augus.github.io/ngAnimate/open in new window

https://www.cnblogs.com/sunyaaa/p/7296633.htmlopen in new window

https://www.w3cschool.cn/angularjs_node/angularjs_node-qkzm27yh.htmlopen in new window

65.1 文本框 高度自适应

//创建一个指令:
.directive('autoHeight', function () {
  function autoHeight(elem) {
    elem.style.height = 'auto';
    elem.scrollTop = 0; //防抖动
    elem.style.height = elem.scrollHeight + 'px';
    elem.parentNode.style.height = elem.scrollHeight + 'px';
  }
  return {
    scope: {},
    link: function (scope, ele, attrs) {
      var oriEle = $(ele).get(0);
      $(oriEle).bind('keyup click', function (e) {
        $(oriEle).focus();
        autoHeight($(this).get(0));
      });
      var timer = setInterval(function () {
        if ($(oriEle).val()) {
          autoHeight(oriEle);
          clearInterval(timer);
        }
      }, 100);
    }
  };
});

AngularJs渲染完毕后执行指定操作 (针对ng-repeat定义的 )

<ul>
  <li ng-repeat="item in items" on-finish-render="callMethod()"> <!--可以直接用on-finish-render,不用callMethod方法   -->
      dummy Text
  </li>
</ul>
.directive('onFinishRender',['$timeout', '$parse', function ($timeout, $parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished'); //事件通知
                        var fun = $scope.$eval(attrs.onFinishRender);
                        if(fun && typeof(fun)=='function'){  
                            fun();  //回调函数
                        }  
                });
            }
        }
    }
}])
// 页面初始化加载事件
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {

 });

65.2 ng-repeat 限定循环次数

ng-repeat="item in items|limitTo:5"  

65.3 date时间转换

{{x.outtime | date:'yyyy-MM-dd hh:mm:ss'}}

AngularJs的controller中格式: (注意: controller需要注入$filter)

 var dateAsString = $filter('date')(item_date, "yyyy-MM-dd hh:mm:ss"); 

65.4 AngularJS实现HTML页面嵌套(嵌入页面)

场景: 有多个页面 需要 地图页面作为 底图,故 将地图改为 独立的页面,有自己的controller.js 和html 页面

image-20210111142942716
image-20210111142942716
  • main.html
 <!--main.html 主页面 -->
<body>
    <div class="ditu" ng-controller="mapLineDetailCtrl">
      <ng-include src="'modules/map/mapLineDetail.html'"></ng-include>
    </div>
    <div class="main">
        <!-- 主页面 -->
    </div>
</body>

说明:mapLineDetail.html 是 地图页面 mapLineDetailCtrl 是对于的 js 代码。

main.html 是主页面,和正常的的写法一样,在页面中引入 需要的 公共页面,同时 2个页面的参数可以互用,所以地图初始化需要的参数,在 跳转 main.html 是带入 ,即可保证实现

63.10 ng-repeat 遍历

说明: ng-repeat 遍历不能存在一样的数据,否则不能正常遍历

63.20 this,,$event

**注:**JS事件向下穿透 所以使用target 存在 明明绑定事件的是父元素,但是选中的确实子元素。故可以用currentTarget

参数网址https://blog.csdn.net/yang1067155909/article/details/97273820open in new window

$($event.target).addClass("tabActive");


$($event.currentTarget).addClass("check")

63.30 ionic 绑定手势

    // 页面初始化完成加载
var height0;
    $timeout(function () {
    	$ionicGesture.on('dragstart',function(e){
            var ss = document.getElementById('tower_content')
            height0 = ss.offsetHeight;
        },angular.element(document.querySelector('#gesturesButton')))

        $ionicGesture.on('drag',function(e){
            let nowHeight = height0 - e.gesture.deltaY
            if(nowHeight <= 600)
            $('#tower_content').css("height",nowHeight+"px");

        },angular.element(document.querySelector('#gesturesButton')))

        $ionicGesture.on('dragend',function(e){
            var ss = document.getElementById('tower_content')
            let height = ss.offsetHeight;
            if(height < 200){/// 小于200 收起来
                $('#tower_content').animate({height:'0px'});
            }else if(height > 500){// 高度大于 500 定死
                $('#tower_content').animate({height:'80%'})
            }else{
            	$('#tower_content').css("height",height+"px");
            }
        },angular.element(document.querySelector('#gesturesButton')))
    }, 2000);

63.40 angularjs 复选框 (需要注意的是 数组形式的参数无法传递到后台,所以可以遍历 拼接成字符串)

<label  ng-repeat="lineType in workLineTypeList">
	      	 	<input type="checkbox"    ng-model="lineType.checked"      ng-click="so($event,'{{lineType.type}}',lineType)"  />
				<span  >{{lineType.name}}</span>
			</label>

//识别项目 复选框 自定义事件
	$scope.selecteds=[];
	$scope.so=function($event,id,o){
		var checkbox = $event.target;
		var action = (checkbox.checked?'add':'remove');
		$scope.updateSelected(action,id,checkbox.name);
	}
	$scope.updateSelected = function(action,id,name){
		if(action == 'add' && $scope.selecteds.indexOf(id) == -1){
			$scope.selecteds.push(id); 
		}
		//========================暂时不能用=========================
//		else{
//		     // 删除时进行返回元素和指定元素不相等的元素
//			$scope.selecteds=$scope.selecteds.filter(function(ele){
//				return ele != id;
//			})
//		}
		if(action == 'remove' && $scope.selecteds.indexOf(id)!=-1){ 
			var idx = $scope.selecteds.indexOf(id);
			$scope.selecteds.splice(idx,1);
				}
		//console.log($scope.selecteds)
	}
//参数处理
var identifyItem='';
    	jQuery.each($scope.selecteds,function(index,item){ //对与数组形式的数据,可以遍历将其拼在以前
    		workLineType+=item+',';
    	})
workLineType=workLineType.substring(0,workLineType.lastIndexOf(","));

跳出循环 用  return false;

63.40 ionic 复选框、单选框使用案例:


	$scope.loadCheck=function(treeList){
		if(treeList!=undefined && treeList.length>0){
			$.each(treeList,function (i,item) {
				// 1.默认选中
				var index=$scope.ids.indexOf(item.id);
				if(index!=-1){//说明存在
					if($scope.checkType=='checkbox'){//多选
						item.checked=true;
					}else{
						item.checked=item.id;// 单选按钮
					}
				}
			});
		}
	}

滚动条

设置滚动条 宽度为 0 实现 隐藏

::-webkit-scrollbar {
            width: 0;
            height: 0px;
        }

65.70 ng-show 实现动画

<style>
    .layer_popover_warp{         
            transition: all linear 0.5s;
            z-index: 30;
            opacity: 1;
        }
    .layer_popover_warp.ng-hide{
            z-index: 0;
            opacity: 0;
        }
</style>  
<div class="layer_popover_warp" ng-show="layerShow"></div>

65.80自定义拦截器

angularJS中把html格式的字符串转成html格式显示,ng-bind-html与trustAsHtml的过滤器

img
img

如果直接 写入 <p style="width:80%;margin-left:50px;font-size:16px;" >{{item.message}} </p> 会把标签 原样输出

img
img
.filter('trust2Html', ['$sce', function ($sce) { //------这个过滤器写在js中   
 return function (text) {
        return $sce.trustAsHtml(text);
  };
}])

使用 <p ng-bind-html="item.message|trust2Html"></p>

截取字符串第一个字符,用于 获取人员名称(剔除姓世)

.filter('getNamefilter', function() {
    return function(value) {
        return value =value.substr(1);
    }
});

<div class="wdzb_detail_item_label overlength">{{itemObj.name| getNamefilter}}</div>

65.90 ng-class

https://blog.csdn.net/qq_37347273/article/details/92104166open in new window

65.100 scope.scope.apply() 按需要强制渲染前端页面

$scope.$apply(function(){
                      $scope.statisticsModule='';
                  })

65.101 监听指定对象数值变化 $watch

    /*监听 detail_item 改变*/
    $rootScope.$watch('userItem', function () {
      $scope.detail_item = $rootScope.userItem;
      $scope.loadData();
    });

65.102常用属性和方法

1.limitTo

// 限定循环次数
<div ng-repeat="dangerRecordDataItem in detail_temp_item.yhqxDetailData | limitTo:3">
</div>


// 截取
{{item.yjz_level_name | limitTo:2:2}}

2. 格式化date日期

{{item.createDate| date:'yyyy-MM-dd'}}

3.特殊字符

<span class="span14 mr10" style="color:#2D64F5;" ng-bind-html="line_temp_item.vg_name|trust2Html"></span>



.filter('trust2Html', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
  };
}])

44 ajax

@RequestParam,参数是通过 URL 查询参数传递的,而不是通过请求体。

@RequestBody

参考网址https://blog.csdn.net/dreamstar613/article/details/61913970open in new window

 @RequestParam(value = "ids",required=false,defaultValue="xx") String ids
     
 @RequestBody Map<String, Object> params    
/**

前端在请求体中 传递变量,后端通过JSONObject 接收
*/
@PostMapping(value = "/spWorkRec")
    public AjaxResult spWorkRec(@RequestBody JSONObject request) {
        JSONArray ids = request.getJSONArray("ids");
        Integer auditStatus = request.getInteger("auditStatus");
        try {
//          wlWorkOpRecService.spWorkRec(ids,auditStatus);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("保存失败");
        }
    }

说明:ajax 有时提交中文 到后台报错,是因为 Content-Type 和参数类型 没定义好 (目前app端遇到过)

​ contentType: "application/json;charset=utf-8", 提交json ,则参数使用JSON.stringify(pjDataArr) 抓我json ,同时 后端用 @RequestBody 来,注入参数

​ contentType: 'application/x-www-form-urlencoded', 表单提交

​ 不能用 headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8','Accept': '/' },

使用Map接收,需要添加 RequestParam 注解

 表单提交用 :headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
 如果传递json 字符串 headers: {'Content-Type': 'application/json;charset=utf-8'}
 如果参数 通过 JSON.stringify(params) 转换了,则后端需要 @RequestBody 注入参数同时 @ModelAttribute 注解无法使用
 注:1.如果后端用 @RequestBody 注解了 需要用 headers: {'Content-Type': 'application/json;charset=utf-8'} 指定
    2.后端如果使用 @ModelAttribute 注解 则 前端 不能JSON.stringify(params) 格式参数,同时  headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
        后端不能使用 @RequestBody
    3.传递 list\数组 需要使用
        3.1 post
        3.2 headers: {'Content-Type': 'application/json;charset=utf-8'}
        3.3 data: JSON.stringify(pjDataArr)
        3.4 @RequestBody
    4.使用Map接收,需要添加 `RequestParam` 注解    

前端get请求存储数据在params种,后端只接受其中一个数值

export function isShowCollect(query) {
  return request({
    url: '/busModule/ocYearSumPlan/isShowCollect',
    method: 'get',
    params: query
  })
}

通过@RequestParam 注解获取

@GetMapping(value = "/isShowCollect")
public AjaxResult isShowCollect(@RequestParam Integer planYear) {
    return AjaxResult.success(ocYearSumPlanService.isShowCollect(planYear));
}

@GetMapping("/user")
public User getUser(@ModelAttribute User user,
                    @RequestParam(value = "username", defaultValue = "Guest") String name,
                    @RequestParam(value = "userage", defaultValue = "0") int age) {
    user.setName(name);
    user.setAge(age);
    return user;
}

也可以讲参数作为路径的一部分,通过@PathVariable 注解 获取到

    /**
     * 获取年度清障计划(年计划汇总)OC_YEAR_SUM_PLAN详细信息
     */
    @GetMapping(value = "/isShowCollect/{planYear}")
    public AjaxResult isShowCollect(@PathVariable("planYear") Long planYear) {
        return AjaxResult.success(ocYearSumPlanService.isShowCollect(planYear));
    }

4.1 dataType返回类型

注:dataType:"json" 用这个类型需要,保证后台返回的数据是json 格式,或者返回数字 1、0 等,这个就是我们常用的形式,如果需要接收的是字符串那么类型需要改为dataType:"text"

4.2 ajax 发送list后台保存 案例

post, headers: {'Content-Type': 'application/json;charset=utf-8'} data: JSON.stringify(pjDataArr) ,@RequestBody

  • 前台ajax
function save(){
	var pjDataArr=new Array();
	var scoreFlag=true;
	$("#relativeBox1 .pjDiv").each(function(index,element){// (关键字:遍历元素,元素遍历)
				//$(this).children('input:eq(1)').css("background-color","rgba(30, 220, 206, 0.4)");
				var addData = {
						applyinfoid:$(this).children('input:eq(0)').val(),
						driverId:$(this).children('input:eq(1)').val(),
						carid:$(this).children('input:eq(2)').val(),
						score:$(this).children('input:eq(3)').val(),
						evaLabel:$(this).children('input:eq(4)').val(),
						evaLabelStr:$(this).children('input:eq(5)').val()
				}
				if(addData.score==null || addData.score==''){
					scoreFlag=false;
				}
				pjDataArr.push(addData);
			});
				console.log(pjDataArr);
			if(scoreFlag){
				loading('正在提交,请稍等...');
				$.ajax({
				    type: "POST",
				    url: "${ctx}/zhcg/zhcgApplyinfo/savePjData",
				    dataType: "json",
				    contentType:"application/json",
				    async:false,
				    data: JSON.stringify(pjDataArr),//JSON.stringify(obj2),
				    success: function(data) {
				    closeTip();
				    	alertx(data.flag);
				    	if(data.status==0){
				    		parent.window.location.reload();
				    	}
				    },
				    error: function() {
				    }
				});
			}else{
				alertx("请对驾驶员进行评价,再提交!")
			}
		}
  • 后端

前端使用 JSON.stringify(pjDataArr) 返回 json 字符串到后端 ,后端使用 @RequestBody 来注入参数

/**
	前端返回的是 json 字符串 (JSON.stringify(pjDataArr) )
	后端使用 @RequestBody  来注入参数
*/
@ResponseBody
@RequestMapping(value = "savePjData")
public ResVO<String>  savePjData(@RequestBody List<ZhcgApplyAvaluate> pjDataArr) {
    ResVO<String> res=new ResVO<String>();
    try {
        zhcgApplyinfoService.savePjData(pjDataArr);
    } catch (Exception e) {
        res.setFlag("评价失败!");
        res.setStatus("1");
        e.printStackTrace();
        return res;
    }
    res.setFlag("评价成功!");
    res.setStatus("0");
    return res;
}

4.3 保存对象点对象到后台去

var paramss={
			id:$scope.emp.id,
			userId:$rootScope.user.id,
			'sysEmpBase.jcTimeStr':item.sysEmpBase.jcTime,
			'sysEmpBase.postEvalTimeStr':item.sysEmpBase.postEvalTime
		};
$.ajax({
			type:"post",//post 请求用data
			url: $rootScope.serverUrl+'/sys/empsInfoSave',
			data:paramss,//如果不用原始的ajax ,传递这种对象里面塞对象,这个结构的数据,需要先序列化对象 $.param(paramss)
			success: function(data) {
				var res=data;
   				 if(res.status=='0'){
   					$ionicLoading.hide();
   			    	$cordovaToast.showShortBottom(data.flag);
   			    	$rootScope.back();
   				 }
			},error: function(data){
				$ionicLoading.hide();
			}
		});
//app 后台 不能用   @ResponseBody
@RequestMapping(value = "savePjData", method = RequestMethod.POST)
public ResponseEntity<ResVO<String>> savePjData(SysEmp emp,HttpServletRequest request,HttpServletResponse response)throws UnsupportedEncodingException {
		ResVO<String> res=new ResVO<String>();
		try{
			sysEmpService.savePjData(emp);
		} catch (Exception e) {
			res.setStatus("-1");
			res.setFlag("系统异常,请联系管理员");
			e.printStackTrace();
		}
		return new ResponseEntity<ResVO<String>>(res, HttpStatus.OK);
	}

4.4 参数存储在请求头中,后端如果不用实体对象接收则通过@RequestHeader 注解

需要说明的是 请求头中无法使用 中文

处理; 前端:encodeURIComponent('中文')

后端; URLDecoder.decode(中文字段)

@PostMapping("/importData")
public AjaxResult importData(HttpServletResponse response,
                             @RequestHeader("teamId")  Long teamId, 
                             @RequestHeader("teamName") String teamName,
                             @RequestHeader("year") Integer year) {
    teamName = URLDecoder.decode(teamName);
    // xxxx
}

4.4 $.param()的含义:序列化对象,返回字符串

var params = {a:300,b:300};
var str = $.param(params);
console.log(str);
	输出结果为:a=1900&b=1900

从前端 传递的参数中取指定 属性的 数据

//后台参数获取 
request.getParameter("XXXX");

4.5 前端传递 对象,包含 数组集合的处理 案例

  • 方法1:前端使用 JSON.stringify(paramss) ,后端使用 @RequestBody 来注入参数 [案例](#4.5.1 方法1)
  • 方法2:考虑需要使用 @ModelAttribute,来获取前台没有获取到的实体对象的其他数据。那么 前台不能使用JSON.stringify(xxx) ,将数据转为json字符串 [案例](#4.5.2 方法2)
  • 方法3:前端处理和方法2一样,后端对数组的处理使用 JSON.parseArray [案例](#4.5.3 方法3)

4.5.1 方法1

前端使用 JSON.stringify(paramss) ,后端使用 @RequestBody 来注入参数 。但是不是最优处理方法,因为无法搭配 @ModelAttribute 使用 get 方法,

var paramss={ 
			id:$scope.item.id,
			userId:$rootScope.user.id,//通过 封装的 $rootScope.http  ajax 方法传递到后台
			engineerId:item.engineerId,
			noticeNumber:item.noticeNumber,
			//projJlNoticeDetailListStr:JSON.stringify(projJlNoticeDetailList)
			projJlNoticeDetailList:projJlNoticeDetailList
		};
$.ajax({
			url: $rootScope.serverUrl+'/noticeInfo/applySave',
			data:JSON.stringify(paramss),
			 contentType:"application/json",//传递参数json字符串,对于后台接收参数
			type:"post",
			dataType:"json",
			async:false,
		 	success: function (data){
		 		var res = data;
				 $ionicLoading.hide();
				if(res.status=='0'){//保存成功
					$cordovaToast.showShortCenter('保存成功!');
					$rootScope.back();
				}else{
					$ionicPopup.alert({//暂不识别
						title: '保存失败,请重新提交!',
						okText:'确定' 
					});
				}
		 	},
		 	error: function (){
		 		 $ionicLoading.hide();
				$cordovaToast.showShortBottom("数据异常,请重试!");
		 	}
		});

4.5.2 方法2

考虑需要使用 @ModelAttribute,来获取前台没有获取到的实体对象的其他数据,,那么 前台不能使用JSON.stringify(xxx) ,将数据转为json字符串

  • 前端
var paramss={ 
			id:$scope.item.id,
			userId:$rootScope.user.id,//通过 封装的 $rootScope.http  ajax 方法传递到后台
			engineerId:item.engineerId,
			noticeNumber:item.noticeNumber,
			reason:item.reason,
			projJlNoticeDetailListStr:JSON.stringify(projJlNoticeDetailList)
		};
$.ajax({
			url: $rootScope.serverUrl+'/noticeInfo/applySave',
			data:paramss,
			contentType:"application/x-www-form-urlencoded",//这个要加,不然报错,发送数据流的类型,
			type:"post",
			dataType:"json",
			async:false,
		 	success: function (data){
		 		var res = data;
				 $ionicLoading.hide();
				if(res.status=='0'){//保存成功
					$cordovaToast.showShortCenter('保存成功!');
					$rootScope.back();
				}else{
					$ionicPopup.alert({//暂不识别
						title: '保存失败,请重新提交!',
						okText:'确定' 
					});
				}
		 	},
		 	error: function (){
		 		 $ionicLoading.hide();
				$cordovaToast.showShortBottom("数据异常,请重试!");
		 	}
		});
  • 后端
@RequestMapping(value = "applySave", method = RequestMethod.POST)
	public ResponseEntity<ResVO<String>> applySave(ProjJlNotice projJlNotice,HttpServletRequest request,HttpServletResponse response, Model model)throws UnsupportedEncodingException {
		ResVO<String> res=new ResVO<String>();
		try{//前端 无法直接传递 数组到 后端,故将 数组 转为json 然后由后台转换 为数组
			String json = request.getParameter("projJlNoticeDetailListStr");//如果不这样获取会出现 转义的情况
			List<ProjJlNoticeDetail> list=Lists.newArrayList();
			if(json!=null && !"".equals(json)){
				JSONArray jArray= JSONArray.fromObject(json);
				Collection collection = JSONArray.toCollection(jArray, ProjJlNoticeDetail.class);//引入net.sf.json包所需要的jar包支持
				Iterator it = collection.iterator();
				while (it.hasNext()) {
					ProjJlNoticeDetail bean= (ProjJlNoticeDetail) it.next();  
					list.add(bean);
				}
			}
			System.out.println(list);
			projJlNotice.setProjJlNoticeDetailList(list);
			projJlNoticeService.activitySave(projJlNotice);
			res.setStatus("0");
			res.setFlag("保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			res.setStatus("-1");
			res.setFlag(e.getMessage());
		}
		return new ResponseEntity<ResVO<String>>(res, HttpStatus.OK);
	}

4.5.3 方法3 (最优)

  • 前端
var paramss={
					id:$scope.item.id,
					userId:$rootScope.user.id,
					comment:$scope.comment,
					materialGhRecordDetailListStr:JSON.stringify($scope.infoList),
					infoFlowImagePath:$scope.item.infoFlowImagePath,
					infoFlowRemark:$scope.item.infoFlowRemark,
					taskId:$scope.item.taskId
			};		
		$ionicLoading.show();
		$.ajax({
			url: $rootScope.serverUrl+'/materialGh/ghApplySave',
			data:paramss,
			type:"post",
			contentType:"application/x-www-form-urlencoded",
			dataType:"json",
			async:false,
		 	success: function (data){
		 		$ionicLoading.hide();
				var res = data;
				if(res.status=='0'){//保存成功
					$rootScope.layer.msg('保存成功!');
					locals.remove("flowData");
					$rootScope.back();
				}else{
					$ionicPopup.alert({//暂不识别
						title: '保存失败,请重新提交!',
						okText:'确定' });
				}
		 	},
		 	error: function (){
		 	}
		});

  • 后端
@ModelAttribute
	public MaterialHbRecord get(@RequestParam(required=false) String id) {
		MaterialHbRecord entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = materialHbRecordService.get(id);
		}
		if (entity == null){
			entity = new MaterialHbRecord();
		}
		return entity;
	}
//领用物资审批保存(待审批)
	@RequestMapping(value = "ghApplySave", method = RequestMethod.POST)
	public ResponseEntity<ResVO<String>> ghApplySave(MaterialGhRecord materialGhRecord,String materialGhRecordDetailListStr,
HttpServletRequest request,HttpServletResponse response) {
		ResVO<String> res = new ResVO<String>();
		try {
			String materialGhRecordDetailList=request.getParameter("materialGhRecordDetailListStr");
			List<MaterialGhRecordDetail> dataList= JSON.parseArray(materialGhRecordDetailList,MaterialGhRecordDetail.class);
//引包 import com.alibaba.fastjson.JSON;
			materialGhRecord.setMaterialGhRecordDetailList(dataList);
			//拼接字符串
			materialGhRecordService.saveData(materialGhRecord);//pc能和app端公用保存方法
			res.setStatus("0");
		} catch (Exception e) {
			e.printStackTrace();
			res.setStatus("-1");
			res.setFlag( e.getMessage());
		}
		return new ResponseEntity<ResVO<String>>(res, HttpStatus.OK);
	}

44. 6 流的形式读取参数

var data={
        		objId:objId,
        		userid:$rootScope.user.id,
        		taskId:taskId        		
        };    
	    $.ajax({
			type: "POST",
			url:$rootScope.serverUrl+"/flowSign/signSave",
			contentType:"application/json;charset=utf-8",
			data:JSON.stringify(data), 
			dataType:'json',
			async: false,
			success: function(data) {
				
			}
		}); 
@RequestMapping(value = "signSave", method = RequestMethod.POST)
public ResponseEntity<ResVO<String>> signSave(HttpServletRequest request,HttpServletResponse response){
    ResVO<String> res = new ResVO<String>();
    StringBuilder sb = new StringBuilder();
String sbString="";
request.setCharacterEncoding("UTF-8");
   try(BufferedReader reader = request.getReader()) {
      char[] buff = new char[1024];
      int len;
      while((len = reader.read(buff)) != -1) {
         sb.append(buff,0, len);
    }
    sbString=sb.toString();
JSONObject jobject = JSONObject.fromObject(sbString);
     
  //电子签名图片保存的路径
  String userid = jobject.getString("userid");

  String objId = jobject.getString("objId");
  return new ResponseEntity<ResVO<String>>(res, HttpStatus.OK);
}

前端参数传递json格式数据,后端不通过实体注入

	@PostMapping("/getYhBihuanStatisData")
	public AjaxResult getYhBihuanStatisData(@RequestBody String queryParam){
		try {
			JSONObject jsonObject = JSONObject.parseObject(queryParam);
			return AjaxResult.success(mapDetailService.getYhBihuanStatisData(jsonObject));
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error(e.getMessage());
		}
	}
<resultMap type="java.util.Map" id="yhBihuanStatisDataResult">
        <result property="yhs" column="yhs" javaType="java.lang.Long" />
        <result property="ybh" column="ybh" javaType="java.lang.Long" />
    </resultMap>

    <select id="getYhBihuanStatisData" resultMap="yhBihuanStatisDataResult" parameterType="com.alibaba.fastjson.JSONObject">
        SELECT
            count(1) yhs,
            sum(case status when '5' then 1 else 0 end) ybh,
            sum(case  when  FIND_TIME like '2022-09%' then 1 else 0 end) byxz,
            sum(case  when  FIND_TIME like '2022-09%' and status = '5' then 1 else 0 end) bybh
        FROM yh_op_record
        WHERE del_flag = '0'
        <!-- status:隐患状态
            1:隐患库(暂存)   2:上报审核中   3:隐患管控中   4:闭环审核中
            5:已闭环(正常)  6:重复上报(DEL_FLAG设为1)  7:误报(DEL_FLAG设为1)
        -->
        AND status != '1'
        <if test="opTeamId!=null and opTeamId != ''">
            AND op_team_id = #{opTeamId}
        </if>
        <if test="opOrgId!=null and opOrgId != ''">
            AND op_org_id = #{opOrgId}
        </if>
    </select>

44.9 ajax 设置全局 header

对于 app 无法使用 UserUtils.getUser() 方法的解决 ,思路:在公共js中 对ajax 设置全局 header

$.ajaxSettings.beforeSend = function(xhr,request){//beforeSend方法用于在向服务器发送请求前添加一些处理函数
			let user =  locals.getObject("user");    // 获取用户信息
		    xhr.setRequestHeader('userId',user.id);//ajax中的setRequestHeader设置请求头
		}
/**
	 * 获取当前用户
	 * 
	 * @return 取不到返回 new User()
	 */
	public static User getUser() {
		if (RequestContextHolder.getRequestAttributes() != null) {
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			String userId = request.getHeader("userId");// APP 访问,,通过ajax 的消息头找到 userId 去查询用户
			if(StringUtils.isEmpty(userId)){
				userId = request.getHeader("userid");
			}
			if (!StringUtils.isEmpty(userId)) {
				User user = get(userId);
				if (user != null) {
					return user;
				}
			} else {
				Principal principal = getPrincipal();
				if (principal != null) {
					User user = get(principal.getId());
					if (user != null) {
						return user;
					}
					user = new User();
					user.setCompany(getOfficeById(ROOT_OFFICE_ID));
					return user;
				}
			}
		}
		User user = new User();
		user.setCompany(getOfficeById(ROOT_OFFICE_ID));
		// 如果没有登录,则返回实例化空的User对象。
		return user;
	}

前端提交 headers: { 'Content-Type': 'application/json;charset=utf-8' }, json 格式,后端如果是java 对象,

通过 @RequestBody User user 注入,如果不是实体对象 可以通过@RequestBody String requestBody 接收,然后转成JSONObject 去获取

@PostMapping("uploadFileForBase64")
public AjaxResult uploadFileForBase64(@RequestBody String requestBody) {
    try {
        JSONObject jsonObject =JSONObject.parseObject(requestBody);
        return basFileUploadService.uploadFileForBase64(jsonObject.get("base64image").toString(),jsonObject.get("moduleName").toString());
    } catch (Exception e) {
        return AjaxResult.error(e.getMessage());
    }
}

4.10 postman使用

汉化: https://gitee.com/hlmd/PostmanCnopen in new window

1. 使用postman做压力测试

2.

需要往后端传递一个map对象

{
    "procInsId":"12",
    "targetTaskDefinitionKey":"34",
    "vars":{"key1": "value1","key2": "value2"}
}
	@PostMapping(value = "/skipToNeedNode")
	public AjaxResult skipToNeedNode(@RequestBody Map<String, Object> allParams) {
		String procInsId = (String) allParams.get("procInsId");
		String targetTaskDefinitionKey = (String) allParams.get("targetTaskDefinitionKey");
		Map<String, Object> vars = (Map<String, Object>) allParams.get("vars");
		try {
//			Map<String, Object> vars = Maps.newHashMap();
//			actTaskService.skipToNeedNode(procInsId,targetTaskDefinitionKey,null,vars);
		} catch (Exception e) {
			e.printStackTrace();
			AjaxResult.error("工作流执行:"+e.getMessage());
		}
		return AjaxResult.success();
	}

post请求,后端没有使用实体对象

可以使用表单提交的方式注入参数,前端请求headers 指定 'Content-Type': 'application/x-www-form-urlencoded'

    /**
     * 签到、签退
     */
    @PostMapping("clockInOut")
    public AjaxResult clockInOut(String type,String abnormalRemark) {
        try {
            String states = odAttendanceRecordService.clockInOut(type, abnormalRemark);
            return AjaxResult.success("操作成功", states);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getLocalizedMessage());
        }
    }

设置Content-Type为application/x-www-form-urlencoded时,请求数据需要被编码为键值对的形式,比如key1=value1&key2=value2

可以使用qs库来将你的JSON对象转换为x-www-form-urlencoded格式,或者自己手动拼接出来

async clockInOut(type,abnormalRemark='') {
    const params= `type=${type}&abnormalRemark=${abnormalRemark}`; // 需要注意这里不是json格式
    const res = await this.$axiosApi('busModule/odAttendanceRecord/clockInOut', params, 'post',{ 'Content-Type': 'application/x-www-form-urlencoded' })
    if (res.code == 200) { }
}

60 JSON

60.1 解析

JSONObject jsonObject = JSONObject.fromObject(result);//将字符串转为JSON 对象
JSONObject rootjson = jsonObject.getJSONObject("ROOT");//

JSONArray infoDataJson = JsonTransformKeyUtil.transToArray(infoJson.getJSONArray("DATA"));// 实体对象 在 CPMS系统中
List<RiskDataVo> riskDataVoList = JSON.parseArray(riskDataJson.toString(),RiskDataVo.class);
List<RiskDataVo> riskDataVoList = JsonUtil.jsonToList(infoDataJson.toString(),new TypeReference<List<RiskDataVo>>(){});
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.9</version>
</dependency>

60.100 解析

var jsonObj={"name":"张三","age":"24","profession":"工程师"};       
console.log(jsonObj.name);
console.log(jsonObj[name]);// 这个写法,可以支持 key值自定义传参的形式          

63开发技巧

63.1. Fiddler

Fiddler

63.2. Fiddler抓取在夜神模拟器安装的软件的包

夜神模拟器wifi代理设置 https://blog.csdn.net/weixin_42670402/article/details/82997947open in new window

打开设置---长按已经连接的wifi记录--修改网络

img
img

主机名设置为当前电脑的ip,断开设置为Fiddler 设置的端口

image-20201121142026648
image-20201121142026648

63.3.eclips无法打开模拟器

打开eclipse的DDMS,点击reset adb,其实相当于重置adb,具体步骤如下:点击windows--show view--other--devices

img
img

63.4.手机调试:

谷歌:chrome://inspect/#devices

edge: edge://inspect/#devices

image-20200914144005221
image-20200914144005221

63.5

https://blog.csdn.net/lucy_100/article/details/49820393open in new window

https://www.jianshu.com/p/66896bec620eopen in new window

64 vscode下关于Live Server的使用

https://blog.csdn.net/zhouwei_doris/article/details/80604604