小仙女是不喝酒的

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

s前端 demo

原生 js 选项卡切换效果

### css

* {
           margin: 0;
           padding: 0;
      }

      .box {
           margin: 20px auto;
      }

      .list {
           height: 20px;
           width: 200px;
      }

      .list li {
           width: 64px;
           float: left;
           list-style: none;
           border: 1px solid red;
      }



      .box div {
           width: 200px;
           height: 200px;
           background: lightblue;
           text-align: center;
           line-height: 200px;
           display: none;
      }

### html

<div class="box">
       <ul class="list">
           <li style="background: blueviolet;">项目1</li>
           <li>项目2</li>
           <li>项目3</li>
       </ul>
       <div style="display: block;">
           项目1
       </div>
       <div>
           项目2
       </div>
       <div>
           项目3
       </div>
   </div>

### js

 var Ali = document.getElementsByTagName("li");
       var Adiv = document.querySelectorAll(".box div");
       for (let i = 0; i < Ali.length; i++) {
           // 把循环的数字赋给Ali中index
           Ali[i].index = i;
           // console.log(Ali[i].index);
           Ali[i].onclick = function () {
               for (let i = 0; i < Ali.length; i++) {
                   Ali[i].style.background = '';
                   Adiv[i].style.display = 'none';
                   Ali[this.index].style.background = 'blueviolet';
                   Adiv[this.index].style.display = 'block';
              }
          }
      }

jquery 选项卡切换效果

##css
* {
margin: 0;
padding: 0;
}

.box {
margin: 20px auto;
}

.list {
height: 20px;
width: 200px;
}

.list li {
width: 64px;
float: left;
list-style: none;
border: 1px solid red;
}
.active{
background: blueviolet;
}


.box div {
width: 200px;
height: 200px;
background: lightblue;
text-align: center;
line-height: 200px;
display: none;
}
.box .actived{
display: block;
}
## html
<div class="box">
<ul class="list">
<li class="active">项目1</li>
<li>项目2</li>
<li>项目3</li>
</ul>
<div class="actived">
项目1
</div>
<div>
项目2
</div>
<div>
项目3
</div>
</div>
## js
$(".list li").click(function(){
$(this).addClass("active").siblings().removeClass("active");
var index = $(this).index();
$(".box div").eq(index).addClass("actived").siblings().removeClass("actived");
})

时间显示和一段文字逐个显示的效果

##css
* {
margin: 0;
padding: 0;
}

#time {
width: 200px;
height: 40px;
border: 1px solid yellowgreen;
margin: 20px auto;
text-align: center;
line-height: 40px;
}

#newcontent {
box-sizing: border-box;
width: 100%;
padding: 60px;
margin: 100px auto;
}

#oldcontent {
display: none;
}
##html
<div id="time">
</div>
<p id="oldcontent">
2021.5.20断断续续加起来我们已经相伴了一年零七个月了,则么感觉有好几年的感觉了.有时候感觉你很心细,但有时候的你又很粗心,我真的是猜不透你心里到底在想什么.你的想法有时候很奇妙,你一般又不会去跟我沟通,我有时候都不确定你有多爱我.真琢磨不透,所以干脆我放弃了思考,不用我的小脑瓜去想那些东西.不说了,不过还是在520这一天说一声我爱你.虽然不表现出来,但是还是想在这些特殊的日子里有一个你制造的惊喜在等着我呀!自己还是会羡慕在这一天手捧鲜花挽着男朋友的小姐姐.好了,下面要开始一波土味情话了,请接招我可以一个人唱歌,一个人喝咖啡,一个人涂鸦,一个人旅行,一个人逛大街,一个人在雨中漫步,一个人听音乐,一个人自言自语,一个人发呆,一个人跳舞,一个人看电视,一个人翻杂志……只有爱你,是我一个人做不到的,希望我们成为最幸福的那一对,转换思想,我不怪你你不懂我,我只怪自己不懂你!我打开笔记,我又落笔放弃了回忆!520,我心依旧!我有一个梦想,简单快乐,从容不违背!我有一个梦想,你,幸福!
</p>
<div id="newcontent">
</div>
## js
window.onload = function () {
setInterval(() => {
fndate()
}, 1000);

}
function fndate() {
var Time = document.getElementById("time")
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var data = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
var time = pull(year) + '-' + pull(month) + '-' + pull(data) + ' ' + pull(hour) + ':' + pull(minute) + ':' + pull(second);
Time.innerHTML = time;
}
// 当每一位的数不够时补零
function pull(number) {
var num;
number > 10 ? num = number : num = "0" + number;
return num
}

var Oldcontent = document.getElementById("oldcontent");
var Newcontent = document.getElementById("newcontent");
var i = 0;
timer = setInterval(() => {
Newcontent.innerHTML = Oldcontent.innerHTML.substring(0, i);
i++;
if (Newcontent.innerHTML == Oldcontent.innerHTML) {
clearInterval(timer);
}
}, 100);

去掉 css 样式默认的浏览器的样式

@charset "UTF-8";
/** 清除内外边距 **/
body, h1, h2, h3, h4, h5, h6, hr, p, blockquote, /* structural elements 结构元素 */
dl, dt, dd, ul, ol, li, /* list elements 列表元素 */
pre, /* text formatting elements 文本格式元素 */
form, fieldset, legend, button, input, textarea, /* form elements 表单元素 */
th, td /* table elements 表格元素 */ {
margin: 0;
padding: 0;
}
/** 设置默认字体 **/
body,
button, input, select, textarea /* for ie */ {
font: 14px/1.5 tahoma, \5b8b\4f53, sans-serif;
}
h1, h2, h3, h4, h5, h6 { font-size: 100%; font-weight: normal;}
address, cite, dfn, em, var { font-style: normal; } /* 将斜体扶正 */
code, kbd, pre, samp { font-family: courier new, courier, monospace; } /* 统一等宽字体 */
small { font-size: 12px; } /* 小于 12px 的中文很难阅读, 让 small 正常化 */
/** 重置列表元素 **/
ul, ol { list-style: none; }
/** 重置文本格式元素 **/
a { text-decoration: none; }
a:hover { text-decoration: underline; }
sup { vertical-align: text-top; } /* 重置, 减少对行高的影响 */
sub { vertical-align: text-bottom; }
/** 重置表单元素 **/
legend { color: #000; } /* for ie6 */
fieldset, img { border: 0; } /* img 搭车:让链接里的 img 无边框 */
button, input, select, textarea { font-size: 100%; } /* 使得表单元素在 ie 下能继承字体大小 */
/* 注:optgroup 无法扶正 */
/** 重置表格元素 **/
table { border-collapse: collapse; border-spacing: 0; }
/* 重置 HTML5 元素 */
article, aside, details, figcaption, figure, footer,header, hgroup, menu, nav, section,
summary, time, mark, audio, video {
display: block;
margin: 0;
padding: 0;
}
mark { background: #ff0; }
/* 设置placeholder的默认样式 */
:-moz-placeholder {
color: #ddd;
opacity: 1;
}
::-moz-placeholder {
color: #ddd;
opacity: 1;
}
input:-ms-input-placeholder {
color: #ddd;
opacity: 1;
}
input::-webkit-input-placeholder {
color: #ddd;
opacity: 1;
}

a{
text-decoration:none;
color:#333;
}
a:hover, a:visited, a:link, a:active {
// 做到只设置一次,就可以使所有a标签的四种状态都和本身颜色保持一致,样式代码自己写
}
<a href="#outer">
outerA
<object><a href="#inner">innerA</a></object>
</a>

input{
border: none;
appearance:none;
-moz-appearance:none;
outline:none;//input标签聚焦不出现默认边框:
-webkit-appearance: none;//用于IOS下移除原生样式
}
input:focus{ outline:none; }//input标签聚焦不出现默认边框:
border: none; appearance:none; -moz-appearance:none; outline:none;//input标签聚焦不出现默认边框: -webkit-appearance: none;//用于IOS下移除原生样式 } //or: input:focus{ outline:none; }//input标签聚焦不出现默认边框:

:-moz-placeholder { /* Mozilla Firefox 4 to 18 */ color:#3c8bee ;; opacity:1; font-size: 0.25rem;text-align: center; }
::-moz-placeholder { /* Mozilla Firefox 19+ */ color:#3c8bee ;; opacity:1; font-size: 0.25rem;text-align: center; }
input:-ms-input-placeholder{ color:#3c8bee ;; opacity:1; font-size: 0.25rem;text-align: center; }
input::-webkit-input-placeholder{ color:#3c8bee ;; opacity:1; font-size: 0.25rem;text-align: center; }

ul, ol, {
  margin: 0;
  padding: 0;
  list-style: none;
}
img {
  vertical-align:top;
  border:none;
}

em,strong {
  font-style:normal;
  font-weight:normal;
}

button{
border:0;

outline:none;
-webkit-appearance: none;//用于IOS下移除原生样式
}
select {
border: none;
appearance:none;
-moz-appearance:none;
-webkit-appearance:none;
/*在选择框的最右侧中间显示小箭头图片*/
background: url("http://ourjs.github.io/static/2015/arrow.png") no-repeat scroll right center transparent;
padding-right: 14px;
}

::-ms-clear,::-ms-reveal{
display: none;
}

font-size: 12px;
-webkit-transform: scale(0.84);
-ms-transform: scale(0.84);
-moz-transform: scale(0.84);
-o-transform: scale(0.84);
transform: scale(0.84);
-webkit-text-size-adjust: none;

img{
vertical-align: middle;
}
//透明度的兼容性的写法
opacity:0;
-ms-filter: 'alpha(opacity=0)';


uniapp中在需要的页面引入
<style scoped>
@import url('./mydetial.css');
@import url('../evaluate/evaluate.css');
</style>

vue2 项目的创建

https://blog.csdn.net/u012396955/article/details/80740031

首先查看是否安装了 npm 和 node

npm -V

node -V

出现版本号就是安装了

安装全局的 vue

在你要创建 vue 的文件夹打开终端输入 npm install --global vue-cli

安装完成之后输入 vue init webpack demo (demo 是你创建的 vue 项目名)

vue2 移动端适配

安装 1. npm install lib-flexible --save

2.npm install postcss-px2rem-exclude --save(解决了当 vue 项目引入第三方插件的时候所有的样式都小了一半) 或者是 npm install postcss-px2rem --save-dev(当引入第三方插件的时候所有的样式都小了一半)

3.在项目 main.js 文件中引入'lib-flexible'

import 'lib-flexible'

4.在 build 文件夹下面的 utils.js 文件中加入代码

const px2remLoader = {

loader: 'px2rem-loader', options: { remUnit: 75,//这是设计稿的尺寸 750/10 exclude: /node_modules|folder_name/i //当引入第三方插件的时候样式不被缩小

}

}

const loaders = options.usePostCSS ? [cssLoader, px2remLoader, postcssLoader] : [cssLoader, px2remLoader]

5.在 node_modules 文件夹下 lib_flexible 文件夹下 flexible.js 中

var width = docEl.getBoundingClientRect().width;

if (width / dpr > 540) { width = 50* dpr; }

中的 width = 50* dpr 改为 width = width * dpr

vue3 移动端适配

1.下载 npm install postcss-pxtorem --save-dev(建议用 postcss-pxtorem 而不是 postcss-px2rem)

2.下载 npm install lib-flexible --save

3.在项目 main.js 文件中引入'lib-flexible'

import 'lib-flexible'

4.在项目根目录下 postcss.config.js 中(没有这个文件夹就自己建一个)写

module.exports = {

plugins: {

autoprefixer: {

overrideBrowserlist: ['Android >= 4.0', 'ios >= 7'],

},

'postcss-pxtorem': {

rootValue: 75, // Vant 官方根字体大小是 37.5

propList: ['*'],

selectorBlackList: ['.norem'], // 过滤掉.norem-开头的 class,不进行 rem 转换

selectorBlackList: ['van'],//过滤掉 vant 中的 px 转成 rem

},

},

};

vue 项目的服务器代理

1.在 config 文件夹下的 index.js 中有一个 proxyTable:{}

 proxyTable: {
// api在以后的页面使用就相当于 /api=== http://localhost/54321/
'/api':{
// 真的服务器的接口地址
target:'http://localhost/54321/',
// 如果是https接口则需要把secure设为true
secure:true,
changeOrigin: true, // 是否是跨域请求?肯定是啊,不跨域就没有必要配置这个proxyTable了.
pathRewirte: {
// 这里是追加链接,比如真实接口里包含了 /api,就需要这样配置.

'/^api': 'api/',
// 等价于
// step 1 /api = http://localhost:54321/
// step 2 /^api = /api + api == http://localhost:54321/api
}
}
},

vue 中 axios 的数据请求

1.在 main.js 中

// 引入axios

import axios from 'axios';

// 将vue改为vue的原型链就可以在组件中使用axios了

Vue.prototype.$ajax = axios;

2.在需要调取的组件里面

 mounted() {
this.requestt();
},
methods: {
// axios的请求
requestt() {
// vue中的data无法通过this直接引用则需要转换
var that = this;
this.$ajax
.post("http://www.baidu.com")
.then(function (res) {
console.log(res.data);
that.info = res.data.data;
console.log(that.info);
})
.catch(function (res) {
console.log(res);
});
},
}

在 vue 中引入 echart

1.在 main.js 中

// 引入echart
import * as echarts from 'echarts';
Vue.prototype.$echarts = echarts;

2.在相应的需要引用 echart 的组件中

## component
<div ref="chart" style="width: 120px; height: 376px"></div>
//通过改变不同的ref值来在一个页面渲染多个echart图表
<div ref="chart1" style="width: 120px; height: 376px"></div>
## js
mounted() {
this.requestt();
},
methods{
// echart的js写法
getEchartData() {
//不同的ref值渲染不同的图表
//const chart = this.$refs.chart1
const chart = this.$refs.chart;
if (chart) {
const myChart = this.$echarts.init(chart);
const option = {
tooltip: {
trigger: "item",
},
legend: {
top: "5%",
left: "center",
},
//修改series中的内容来实现不同的图标的形成
series: [
{
name: "访问来源",
type: "pie",
radius: ["40%", "70%"],
avoidLabelOverlap: false,
label: {
show: false,
position: "center",
},
emphasis: {
label: {
show: true,
fontSize: "40",
fontWeight: "bold",
},
},
labelLine: {
show: false,
},
data: [
{ value: 1048, name: "搜索引擎" },
{ value: 735, name: "直接访问" },
{ value: 580, name: "邮件营销" },
{ value: 484, name: "联盟广告" },
{ value: 300, name: "视频广告" },
],
},
],
};
myChart.setOption(option);
window.addEventListener("resize", function () {
myChart.resize();
});
}
this.$on("hook:destroyed", () => {
window.removeEventListener("resize", function () {
myChart.resize();
});
});
},
}

echart 的部分样式的调整

Xaxis:{ axisLabel: { interval: 0, //强制文字产生间隔 rotate: "45", //旋转角度 },

} //滚动条

dataZoom: [ //滚动条 { type: 'slider', start: 0, end: 35, bottom: 5, show: true, width: '100%', height: 10, left: 'center', backgroundColor: 'rgb(60,114,209)', height: '4', fillerColor: '#fff', borderColor: 'rgb(60,114,209)', textStyle: { color: 'transparent', }, }, ], //图标的位置 legend //整个图表的位置 grid //图像的位置 series 中 center series: [ {

                  radius: ["35%", "45%"] // 这个属性修改圆环宽度

center: ['30%', '50%'],//这个属性修改圆环位置

]

柱状图的渐变色

color: {

type: "linear",

x: 0,

y: 1,

x2: 0,

y2: 0,

colorStops: [

{

offset: 1,

color: "#4dd2ff",

},

{

offset: 0,

color: "rgba(77,210,255,0)",

},

{

offset: 0.22,

color: "#4dd2ff",

},

],

},

uniapp 中嵌套 vue

 

 

前端自己用 node 开一个服务器

https://blog.csdn.net/muzidigbig/article/details/88550503

获取微信小程序的 appenid

enter() {
let _this = this;
uni.login({
provider: 'weixin',
success: function (loginRes) {
// 获取用户信息 当登录小程序时会获取自己的appendid
var code = loginRes.code;
_this.tui
//后端需要身份验证
.request('/api/auth', 'GET', {
code: code,
})
.then(
res => {
if (res.code == 10000) {
_this.isLogin = true;
//把自己从后端获取的身份认证的信息保存在Authorization中,在以后的页面中就可以使用
uni.setStorageSync('Authorization', res.value);
setInterval(() => {
_this.time--;
if (_this.time == 0) {
clearInterval(_this.timer);
}
}, 1000);

setTimeout(() => {
_this.goHome();
}, 3000);
} else {
_this.tui.toast(res.msg, 2000, false);
}
},
error => {
_this.tui.toast(error, 2000, false);
}
);
},
});
},
swiper() {
let _this = this;
//后端要求要传身份验证信息,先获取你存储的
var Authorization = uni.getStorageSync('Authorization');
this.tui
.request(_this.api.swiperList, 'GET', {
//接口请求传入到后端接口上
Authorization: Authorization,
})
.then(
res => {
if (res.code == 10000) {
this.swiperList = res.value;
console.log(this.swiperList)
} else {
this.tui.toast(res.msg, 2000, false);
}
},
error => {
this.tui.toast(error, 2000, false);
}
);
},

uniapp 中从列表页到详情页传参

//传输数据的页面
todetail(item){
uni.navigateTo({
url:'../details/details?item='+encodeURIComponent(JSON.stringify(item))
})
}
//接受数据的页面
onLoad(option) {
const item = JSON.parse(decodeURIComponent(option.item));
this.id = item.id;
console.log(this.id);
},

字符串的拼接

 

/api/event/public/${this.id}

跳转到详情页时需要传入 id 获取相应的数据

去掉后端返回的带有标签的数据

1. record.content="<p>11111</p>"
2. const content = record.content.replace(/<.*?>/ig,"")
3. console.log(content ); // 1111

自定义指示点的轮播图

<!-- banner -->
<view class="uni-margin-wrap">
<view class="uni-margin-wrap">
<swiper class="swiper" circular autoplay :interval="interval" :duration="duration" @change="changeSwiper">
<swiper-item v-for="(item, index) in swiperList" :key="index" @click="toawiper(item)">
<image class="swiper-img" :src="item.cover_image" mode=""></image>
</swiper-item>
</swiper>

<view class="swiper-dots" v-for="(item, i) in swiperList" :key = "i">
<text class="swiper-title" v-if="i == checkWiperItem">{{ item.title }}</text>
<view class="radio-box">
<text v-for="(item, i) in swiperList" :key = "i" :class="[i == checkWiperItem?'check-radio':'radio']"></text>
</view>
</view>
</view>
</view>

##js
changeSwiper(e) {
// console.log( '改变当前事件',e.detail.current);
this.checkWiperItem = e.detail.current;
},
##css
.uni-margin-wrap {
width: 100%;
position: relative;
}

.swiper {
height: 450rpx;
}

.swiper-item {
width: 100%;
display: block;
height: 450rpx;
position: relative;
}

.swiper-img {
width: 101%;
height: 450rpx;
}

.circle-box {
position: absolute;
bottom: 0;
right: 30rpx;
height: 60rpx;
line-height: 60rpx;
width: 30%;
}

.circle {
width: 20rpx;
height: 20rpx;
border-radius: 50%;
background: #FFFFFF;
display: inline-block;
margin-right: 10rpx;

}

.swiper-dots {
position: absolute;
bottom: 0;
left: 0;
width: 100%;

display: flex;
justify-content: space-between;
align-content: center;
}

.swiper-title {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 60rpx;
line-height: 60rpx;
padding-left: 30rpx;
color: #FFFFFF;
background: rgba(0, 0, 0, 0.3);
}

.radio-box {
width: 200rpx;
height: 30rpx;
position: absolute;
right: 10rpx;
bottom: 10rpx;
display: flex;
flex-direction: row;
z-index: 100;
}

.radio {
width: 20rpx;
height: 20rpx;

margin-left: 10rpx;
border-radius: 50%;
}

.check-radio {
width: 20rpx;
height: 20rpx;
margin-left: 10rpx;
border-radius: 50%;


}

.swiper-title {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 60rpx;
line-height: 60rpx;
padding-left: 30rpx;
color: #FFFFFF;
background: rgba(0, 0, 0, 0.3);
}


.swiper-title {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 60rpx;
line-height: 60rpx;
padding-left: 30rpx;
color: #FFFFFF;
background: rgba(0, 0, 0, 0.3);
}

.uni-margin-wrap1 {
width: 100%;
height: 100rpx;
border-bottom: 3px solid #f1f1f1;
}

效果图

 

uniapp 横向滑动条

##html
<view class="list-box">
<view class="content">
<scroll-view scroll-x="true" class="scroll">
<view class="box" v-for="(item, index) in picture" :key="index">
<image :src="item.image" class="images"></image>
</view>
</scroll-view>
</view>
</view>
#css
.content {
margin-top: 20rpx;
}

.content .scroll {
width: 100%;
overflow: hidden;
white-space: nowrap;
}

.content .scroll .box {
display: inline-block;
width: 100%;
height: 500rpx;
margin-right: 30rpx;
}

.content .scroll .box .images {
width: 100%;
}

.content .scroll .box:last-child {
margin-right: 0;
}

uniapp 选项卡效果

<view class="tab-title">
<text class="tab-text" v-for="(item,index) in category" :key="index" @click="activetab(index)"
:class="index == activeclass ? 'active-text':'tab-text'">{{item.title}}</text>
</view>
<view class="list-box" v-if="activeclass == 0">
内容一
</view>
<view class="list-box" v-if="activeclass == 1">
内容二
</view>

##js
<script>
export default{
data(){
return{
activeclass:0,
category: [{
title: "推广海报"
}, {
title: "商学院"
}, {
title: "官方活动"
}],
}
}
methods:{
activetab(i) {
this.activeclass = i
},
}
}
</script>
##css
.tab-title {
width: 100%;
display: flex;
justify-content: space-around;
height: 100rpx;
line-height: 100rpx;
border-bottom: 3px solid #f6f6f6;

.tab-text {
font-size: 30rpx;
color: #666666;
}

.active-text {
font-size: 30rpx;
color: #000000;
font-weight: bolder;
}
}

在页面中自定义导航栏信息

uni.setNavigationBarTitle({
title: this.form.eventType == 'thing' ? '我要说事' : this.form.eventType == 'complaint' ? '我要投诉' : '',
});

js 填充

Math.pow(5, 2) == 5 ** 2; //25

js 运算符优先级

JavaScript 运算符优先级值
值 运算符 描述 实例
20 ( ) 表达式分组 (3 + 4)

19 . 成员 person.name
19 [] 成员 person["name"]
19 () 函数调用 myFunction()
19 new 创建 new Date()

17 ++ 后缀递增 i++
17 -- 后缀递减 i--

16 ++ 前缀递增 ++i
16 -- 前缀递减 --i
16 ! 逻辑否 !(x==y)
16 typeof 类型 typeof x

15 ** 求幂 (ES7) 10 ** 2

14 * 乘 10 * 5
14 / 除 10 / 5
14 % 模数除法 10 % 5

13 + 加 10 + 5
13 - 减 10 - 5

12 << 左位移 x << 2
12 >> 右位移 x >> 2
12 >>> 右位移(无符号) x >>> 2

11 < 小于 x < y
11 <= 小于或等于 x <= y
11 > 大于 x > y
11 >= 大于或等于 x >= y
11 in 对象中的属性 "PI" in Math
11 instanceof 对象的实例 instanceof Array

10 == 相等 x == y
10 === 严格相等 x === y
10 != 不相等 x != y
10 !== 严格不相等 x !== y

9 & 按位与 x & y
8 ^ 按位 XOR x ^ y
7 | 按位或 x | y
6 && 逻辑与 x && y
5 || 逻辑否 x || y
4 ? : 条件 ? "Yes" : "No"

3 = 赋值 x = y
3 += 赋值 x += y
3 -= 赋值 x -= y
3 *= 赋值 x *= y
3 %= 赋值 x %= y
3 <<= 赋值 x <<= y
3 >>= 赋值 x >>= y
3 >>>= 赋值 x >>>= y
3 &= 赋值 x &= y
3 ^= 赋值 x ^= y
3 |= 赋值 x |= y

2 yield 暂停函数 yield x
1 , 逗号 7 , 8

登录 demo

<template>
<view class="login" :style="'min-height:'+height" style="">
<view class="" align="center">
<image class="login-img" src="../../static/login/login.png" mode=""></image>
</view>

<input class="login-phone" type="text" placeholder="手机号码" />
<view class="login-infor">
<input class="infor" type="text" placeholder="短信验证码" />
<text class="login-code" v-if="show" @click="time()" > | &nbsp;&nbsp;获取验证码</text>
<text class="login-code" v-if="none">| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{number}}s</text>
</view>

<button class="login-btn" type="default">确认登录</button>
<view class="agree" align="center">
点击确定,即表示已阅读并同意<text class="clause">《注册会员服务条款》</text>
<view class="or">

</view>
<view class="wx-login">
微信一键登录
</view>
</view>

</view>
</template>

<script>
export default {


data() {
return {
height: '',
number:59,
show:1,
none:0,
second:''
}
},

/**
* 生命周期函数--监听页面加载
*/
onLoad() {
uni.getSystemInfo({
success: (res) => {
console.log(res)
this.height = res.windowHeight + 'px'
}
})
},

methods: {

time(){
var _this = this;
this.show = 0;
this.none = 1
// setInterval (function () {
// this.number--;
// }, 1000);
let timer =setInterval(() => {
_this.number--;
if (_this.number == 0) {
clearInterval(timer);
this.show = 1;
this.none = 0
}
}, 1000);


// setInterval(function(){
// this.number--,
// },1000);


}
}
}
</script>

<style lang="scss" scoped>
.login {
width: 100%;
padding: 0 5%;

.login-img {
display: black;
width: 170rpx;
height: 170rpx;
margin: 115rpx auto;
}

.login-phone {
width: 90%;
margin: 35rpx auto;

border-radius: 50rpx;
color: #bebec0;
font-size: 28rpx;
height: 85rpx;
line-height: 85rpx;
margin-bottom: 25rpx;
padding-left: 35rpx;
}
.login-infor{
display: flex;
width: 95%;
margin: 0 auto;
.infor{
width: 65%;
margin: 35rpx auto;

border-radius: 50rpx 0 0 50rpx;
color: #bebec0;
font-size: 28rpx;
height: 85rpx;
line-height: 85rpx;
margin-bottom: 25rpx;
padding-left: 35rpx;
float: left;
}
.login-code{
width: 32%;
color: #cdcdcd;
font-size: 26rpx;
margin: 35rpx auto;

border-radius: 0 50rpx 50rpx 0;
color: #bebec0;
font-size: 28rpx;
height: 85rpx;
line-height: 85rpx;
margin-bottom: 25rpx;

}
}

.login-btn {
margin: 50rpx auto;
width: 94%;

font-size: 32rpx;
color: #ffffff;
height: 90rpx;
line-height: 90rpx;
text-align: center;
border-radius: 50rpx;
}

.agree {
margin-top: 110rpx;
font-size: 24rpx;
color: #666666;

.clause {
color: #6690d7;
}

.or {
margin: 60rpx 0;
}

.wx-login {
width: 290rpx;
height: 85rpx;
line-height: 85rpx;

color: #ffffff;
font-size: 30rpx;
border-radius: 50rpx;
margin: 0 auto
}
}
}
</style>

效果图

 

this 的指向

在方法中,this指向所有者对象
在单独情况下,this指向的是全局对象
在函数中,this指向全局
在严格模式下,this指向underfined
在事件中,this指向接收事件的元素

call 和 apply

<p id = "demo"></p>
<script>
var person2 = {
name:"liming",
age :32
}
var person1 = {
num:function(){
return this.name + '' + this.age
}
}
var x = person1.num.call(person2);
document.getElementById("demo").innerHTML = x
</script>

js 事件

onabort

onabort事件当加载图片没完成时被中断时调用  	只支持img
<img src="image_w3default.gif" onabort="alert('Error: Loading of the image was aborted')" />

转义字符

代码结果描述
' ' 单引号
" " 双引号
\ \ 反斜杠

例如:

var x = '中国是瓷器的故乡,因此 china 与"China(中国)"同名。';
//中国是瓷器的故乡,因此 china 与"China(中国)"同名。

正则

uniapp 富文本

<rich-text class="lgjc_content" :nodes="options.title3"></rich-text>
options.title3是后端文本的内容

显示此刻时间及距离具体莫一天的时间

## html
<div class="top">
<span>距离2026-7-15还有</span>
<span id="count"></span>
</div>

<div id="time"></div>
## js
// 倒计时
function timeout() {
var Count = document.getElementById('count');
// 获取当下的时间
var d = new Date();
// 最终的时间
var our = new Date('2026 / 7 / 15 00:00:00');
// 相差的秒数
var ms = (our.getTime() - d.getTime()) / 1000;
// 获取天数
var d = parseInt(ms / (24 * 60 * 60));
// 获取小时
ms %= 24 * 60 * 60;
var h = parseInt(ms / (60 * 60));
ms %= 60 * 60;
var m = parseInt(ms / 60);
var s = parseInt(ms % 60);
Count.innerHTML = d + '天' + h + '小时' + m + '分钟' + s + '秒';
}

// 显示当前时间
window.onload = function () {
setInterval(() => {
fndate();
timeout();
}, 1000);
};
function fndate() {
var Time = document.getElementById('time');
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var data = date.getDate();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
var str = '';
var week = new Date().getDay();
if (week == 0) {
str = '星期日';
} else if (week == 1) {
str = '星期一';
} else if (week == 2) {
str = '星期二';
} else if (week == 3) {
str = '星期三';
} else if (week == 4) {
str = '星期四';
} else if (week == 5) {
str = '星期五';
} else if (week == 6) {
str = '星期六';
}
var time = '当前时间' + pull(year) + '-' + pull(month) + '-' + pull(data) + ' ' + pull(hour) + ':' + pull(minute) + ':' + pull(second) + str;
Time.innerHTML = time;
}
// 当每一位的数不够时补零
function pull(number) {
var num;
number > 10 ? (num = number) : (num = '0' + number);
return num;
}

uniapp 中自动更新

//app自动更新
autoUpdate: function() {
var httpUrl = this.tui.interfaceUrl();
uni.request({
url: httpUrl + "/sys/version/latest", //仅为示例,并非真实接口地址。
method: 'POST',
data: {type: 'people'},
header: {
'content-type': 'application/json' //自定义请求头信息
},
success: (res1) => {
var serverVersion = "";
var clientVersion = plus.runtime.version;
var versionObj = res1.data.data;
console.log("客户端版本:" + clientVersion);
console.log(res1);
console.log("客:" + versionObj);

uni.getSystemInfo({
success: function(res2) {
var platform = res2.platform;
if (platform == "ios") {
serverVersion = versionObj.ver;
} else if (platform == "android") {
serverVersion = versionObj.ver;
}
console.log("服务端版本:" + serverVersion);
if (serverVersion != null && serverVersion != "" && clientVersion != serverVersion) {
uni.showModal({
title: '有新的更新,是否前往下载?',
content: versionObj.verlog,
success: function(res3) {
if (res3.confirm) {
if (platform == "ios") {
plus.runtime.openURL(versionObj.downurl);
} else if (platform == "android") {
if (versionObj.downurl != null) {
plus.runtime.openURL(httpUrl + '/' + versionObj.downurl);
}
}
} else if (res3.cancel) {
//this.noticeTips();
}
}
});
}
else {
this.tui.toast('当前版本为最新版本', 2000, true);
}
}
});

},
complete: () => {}
});
},

一个盒子在另一个盒子上下左右居中

《html代码》
<div class="box"><div class="center">上下左右居中</div></div>
《css样式》当不知道盒子的宽度和高度时
<1>
.box {
width: 500px;
height: 500px;
background: forestgreen;
position: relative;
}
.center {
width: 200px;
height: 200px;
background: darkcyan;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
<2>
.box {
width: 500px;
height: 500px;
background: forestgreen;
position: relative;
}
.center {
width: 200px;
height: 200px;
background: darkcyan;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<3>
.box {
width: 500px;
height: 500px;
background: forestgreen;
display: flex;
justify-content: center;
align-items: center;
}
.center {
width: 200px;
height: 200px;
background: darkcyan;
}

vue 积累

vue2

浏览器显示小图标

1.找一张 24px 大小的图片然后命名为 favicon.ico 放到根目录下

 

2.在 build 文件夹下 webpack.base.conf.js 中添加添加代码

const HtmlWebpackPlugin = require("html-webpack-plugin");

plugins: [

new HtmlWebpackPlugin({

template: "index.html",

favicon: "favicon.ico",

inject: true

})

],

 

vue 中图片放在 assets 中和 static 中的区别

1.

assets 文件夹在 src 里面,所以当打包的时候回经过编译,但是 static 文件里面的东西不会编译,所以推荐 assets 文件夹里面放自己的东西,然后 static 里面放别人的东西

2.assets 和 static 里面的图片在 html 页面里面都可以使用,当动态切换的时候 static 里面的可以用但是 assets 里面的不会显示所以用 require 请求

 

uniapp 中 swiper 高度自带的 150px 修改

<template>
<view style="width:100%;">
<swiper :style="{height:`${height}`}" :indicator-dots="true" :autoplay="true" :interval="2000" :duration="500"
:circular="true">
<swiper-item style="width: 100%;" v-for="it in imgs" :key="it.id">
<image :src="it.url" mode="widthFix" class="img" @load="onLoadImg"></image>
</swiper-item>
</swiper>
</view>
</template>

<script>
export default {
data() {
return {
imgs:[{url:'../../static/img/banner1.jpg',id:1},{url:'../../static/img/banner2.jpg',id:2},
{url:'../../static/img/banner3.jpg',id:3},{url:'../../static/img/banner4.jpg',id:4},
{url:'../../static/img/banner5.jpg',id:5}],
height:''
}
},
methods: {
onLoadImg:function(e){
this.height = e.detail.height + 'rpx';
},
}
}
</script>

<style>
.img{
display: block;//默认是inline-block 会有几px的空白
border: none;
width: 100%;
height: auto;
}
</style>

在小程序中打开小程序

uni.navigateToMiniProgram({
appId: 'wxc338b0f0d384780f', //要加载的小程序的appid
success(res) {
// 打开成功
},
});

字符串的方法

function slistr(str, m, n) {
return str.slice(m, n);
}

// slice截取字符串部分包括最小值不包括最大值

let strsli = slistr('chinhelloworld', 2, 7);

console.log(strsli); //inhel

let strsli1 = slistr('chinhelloworld', -7, -2);

console.log(strsli1); //lowor;

// 如果说只传入一个数的话就是所传的值到字符串的最后一位

let strsli2 = slistr('chinhelloworld', -7);

console.log(strsli2); //loworld;

let strsli3 = slistr('chinhelloworld', 3);

console.log(strsli3); //nhelloworld

function substr(str, m, n) {
return str.substring(m, n);
}

//substring和slice取值方式一样,但是不接受负的取值

let strsli = substr('chinhelloworld', 2, 7);

console.log(strsli); //inhel

let strsli1 = substr('chinhelloworld', -7, -2);

console.log(strsli1); //空

let strsli3 = substr('chinhelloworld', 3);

console.log(strsli3); //nhelloworld

function sub(str, m, n) {
return str.substr(m, n);
}

// substr传一个数的时候和slice一样,传两个数值的时候第一位数表示的是开始的位置包括开始,第二位数表示的截取几位

let strsli = sub('chinhelloworld', 2, 7);

console.log(strsli); //inhello

let strsli1 = sub('chinhelloworld', -7, -2);

console.log(strsli1); //空

// 如果说只传入一个数的话就是所传的值到字符串的最后一位

let strsli2 = sub('chinhelloworld', -7);

console.log(strsli2); //loworld;

let strsli3 = sub('chinhelloworld', 3);

console.log(strsli3); //nhelloworld

vuex

1.新创建文件夹 store 建立文件 store.js 文件

 

2.store.js 文件首先引入 vue 和 vuex 并且抛出初始化数据

 

3.在相应需要的页面获取 count 的值

 

4.通过 getters 和 mutations 来进行数据的计算

 

 

在相应的页面

 

 

5.也可以通过 actions 来计算 count 的值

 

在相应的页面取值

 

6.可以用辅助函数来简写获取值

 

 

 

promise 的用法

例如在商品详情页中我们好几处地方调用一个接口但是相应的处理不同的数据

//总的地方抛出调出的结果
getsession(regin, product) {

return new Promise((resolve, reject) => {

axios

.get("http://baidu.com", {

parmas: {

regin: regin,

product: product

}

})

.then(res => {

resolve(res);

})

.catch(error => {

reject(error);

});

});

},

调用的地方

getsession(regin, product).then(res => {
if (res.code == 0) {
} else {
console.log('error');
}
});

iframe 的设置

<iframe src="./ads_top_tian.html" allowtransparency="true" style="background-color=transparent" title="test" frameborder="0" width="470" height="308" scrolling="no"></iframe>

<iframe src ="/index.html" width="200" height="300" frameborder="0" align = "right" allowtransparency = "true" scrolling = "no" style="background-color=transparent" title="test" >

透明度 allowtransparency="true" style="background-color=transparent"

不要滚动条scrolling="no"

位置的设置align = "right"

frameborder:是否显示边框,1(yes),0(no)

name:框架的名称,window.frames[name]时专用

vue 中父传子

子组件页面

<template>
<div>
<h2>子组件的部分</h2>
<h4>{{ message }}</h4>
</div>
</template>
<script>
export default {
props: ["message"],
data() {}
};
</script>

父组件页面

<template>
<div>
<child message="你不好"></child>
</div>
</template>
<script>
import child from "@/components/children.vue";
export default {
components: { child },
data() {
},
};

父组件可以动态绑定

<template>
<div>
<child :message="parenrmsg"></child>
</div>
</template>
<script>
import child from "@/components/children.vue";
export default {
components: { child },
data() {
return {
parenrmsg: "这是动态绑定"
};
},
methods: {}
};
</script>

vue 中子传父

子页面

<template>
<div>
<h2>子组件的部分</h2>
<h5 @click="messagesent()">点击哦,要传输了</h5>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
messagesent() {
this.$emit("childmesage", "这是子组件的信息传过来啦");
}
}
};
</script>

父页面

<template>
<div>
<child @childmesage="parentrece"></child>
</div>
</template>
<script>
import child from "@/components/children.vue";
export default {
components: { child },
data() {
return {
};
},
methods: {
parentrece(data) {
console.log(data);
},
}
};
</script>

隐藏元素是否占空间

隐藏不占空间
 

pc 端适配

const baseWidth = 1920;
const baseHeight = 1080;
let timer = null;
let calcScale = function () {
let windowInnerWidth = window.innerWidth;
let windowInnerHeight = window.innerHeight;
// let ratioW = baseWidth / windowInnerWidth;
let ratioW = windowInnerWidth / baseWidth;
// let ratioH = baseHeight / windowInnerHeight;
let ratioH = windowInnerHeight / baseHeight;
console.log(windowInnerWidth, windowInnerHeight);
document.body.style.width = baseWidth + 'px';
document.body.style.height = baseHeight + 'px';
document.body.style.transformOrigin = 'left top';
document.body.style.transform = `scale(${ratioW})`;
};
calcScale();
window.onresize = function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(calcScale, 300);
};

流体布局和响应式布局

就是随着浏览器宽度变化而内容宽度随着变化

width:calc(25% - 4px);

流体布局是将一行的内容按照比例进行压缩; 响应式布局是,当宽度小于一定比例时,将一行的内容分两行放置。

todolist 例子

<template>
<div>
<h1>一个todo的例子</h1>
<!--
1.双向绑定,让input中输入的内容能获取到
2.点击添加放到页面中,可以多次放入建立一个循环列表
3.删除的时候已知下标删除相对应的下标在数组中array.splice(index,1)
-->
<div>
<input type="text" v-model="message" />
<button @click="addmess">add</button>
</div>
<ul v-for="(item, index) in list" :key="index">
<li>{{ item }} <button @click="del(index)">del</button></li>
</ul>
</div>
</template>

<script>
export default {
data() {
return {
message: "",
list: []
};
},
methods: {
addmess() {
this.list.push(this.message);
this.message = "";
},
del(index) {
this.list.splice(index, 1);
}
}
};
</script>
<style scoped></style>

vue 中文件夹的引入

es6 中 js 文件导出,vue 页面引用

整体js导出
export const configcontent = {
config,
configdata
}
vue页面引用
important configcontent from './components/config'
return{
config:configcontent.config,
configdata:configcontent.config,
}
单个js导出
const config = {
},
const configdata = {
}
export {config,configdata};
vue引入
important {config,configdata} from './components/config'
return{
config,
configdata,
}

es6

块级作用域

let

const

变量的结构赋值

数组的结构赋值时一一对应的,对象的结构赋值变量与属性名必须一样

数组的结构赋值

let[a,b,c] = [1,2,3]	
console.log(a,b,c) //1,2,3

对象的解构赋值

let{a,b} = {a:1 ,b:2}	
console.log(a,b) //1,2

字符串的结构赋值

let[abcde] = 'hello';
console.log(abcde) //hello

字符串新增方法

字符串的方法at

const str = 'hello';
console.log(str.at(0)) //h
console.log(str.at(-1)) //o

数组的扩展

扩展运算符

...把数组转换成一个参数序列
function f(q,w,e,r){
return q + '-' + w + '-' + e + '-' + r + '-' + t;
}
const fn = [3,6];
consloe.log(f(1,...fn,6,...[9])) //1,3,6,6,9

替换函数apply方法

function fn(x, y, z) {
return x + '-' + y + '-' + z;
}
var arg = [3, 5, 8];
// apply(),第一个是this指向,第二个可以把数组变为一个字符串
console.log('es5apply方法', fn.apply(null, arg)); //apply方法 3-5-8
console.log('es6的写法', fn(...arg)); //es6的写法 3-5-8

扩展运算符的用法

let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1.push(...arr2);
console.log(arr1); //[0, 1, 2, 3, 4, 5]

对象的扩展

当key和value相同时可以直接写key
let birth = '2022/11/22';
const person = {
name:'小红',
birth, //等同于birth:birth
}

this的指向

当以函数的情况调用的时候,this是window
当以方法的时候调用的时候,this指向的就是调用的那个对象
当是构造函数调用的时候,this就是新构造的那个对象

修改this指向

call(),apply(),bind()是函数里方法

call和bind的传值一样,第一个都是this指向,后面依次是传的值,但是bind会返回一个新的函数,所以的重新调用,后面加()。apply的方法是传两个参数,第一个是this指向,第二个是一个数组。数组里面依次是对应的传值
var name = '小明',
age = 13;
var obj = {
name: '小王',
objAge: age,
myfun: function () {
console.log(this.name + '年龄' + this.age);
},
myfn: function (come, togo) {
console.log(`${this.name}年龄${this.age}来自${come}去${togo}`);
},
};
var db = {
name: '德玛',
age: 99,
};
console.log(obj.objAge); //13
console.log(obj.myfun.call(db)); //德玛年龄99
console.log(obj.myfun.apply(db)); //德玛年龄99
console.log(obj.myfun.bind(db)()); //德玛年龄99
console.log(obj.myfn.call(db, '成都', '上海')); //德玛年龄99来自成都去上海
console.log(obj.myfn.apply(db, ['成都', '上海'])); //德玛年龄99来自成都去上海
console.log(obj.myfn.bind(db, ['成都', '上海'])()); //德玛年龄99来自成都,上海去undefined
console.log(obj.myfn.bind(db, '成都', '上海')()); //德玛年龄99来自成都去上海

手机号码中间为*号显示

var phone="17726928842";

var hidden = phone.substring(0,3)+"****"+phone.substring(7)

console.log(hidden) //177****8842

闭包

定义:一个函数有权访问另一个函数中的变量

优点:保存变量不受外界的影响,形成不销毁的栈变量

缺点:不当使用导致内容泄露

解决办法:使用结束后把变量的值赋值为null

数组排序

window.onload = function () {
var arr = [3, 6, 1, 0, 3, 5, 1, 7];
arr.sort();
console.log(arr);
};

vue项目所用的工具库

day.js 处理时间和日期

安装
npm install dayjs
使用
import dayjs from 'dayjs'

setInterval(() => {
this.daydata = dayjs().format('YYYY-MM-DD HH:mm:ss');
}, 1000); //2022-03-22 08:45:39

flv.js 视频播放器,可以使浏览器在不借助flash插件的情况下播放flv

安装
npm install flv.js
使用
<video autoplay controls width="100%" height="500" id="myVideo"></video>
import flvjs from 'flv.js';
// 页面渲染完成后执行
if (flvjs.isSupported()) {
var myVideo = document.getElementById('myVideo');
var flvPlayer = flvjs.createPlayer({
type: 'flv',
url: 'http://localhost:8080/test.flv', // 视频 url 地址
});
flvPlayer.attachMediaElement(myVideo);
flvPlayer.load();
flvPlayer.play();
}

Animate.css css3动画

安装
npm install animate.css
使用
<h1 class="animate__animated animate__bounce">An animated element</h1>
import 'animate.css'

直接给标签加动画class名

原生点击跳转到相应的位置,锚点

//html

<nav>
<a href="#page-1">1</a>
<a href="#page-2">2</a>
<a href="#page-3">3</a>
</nav>
<div class="scroll-container">
<div class="scroll-page" id="page-1">1</div>
<div class="scroll-page" id="page-2">2</div>
<div class="scroll-page" id="page-3">3</div>
</div>

//css

a {
display: inline-block;
width: 50px;
text-decoration: none;
}
nav, .scroll-container {
display: block;
margin: 0 auto;
text-align: center;
}
nav {
width: 339px;
padding: 5px;
border: 1px solid black;
}
.scroll-container {
width: 350px;
height: 200px;
overflow-y: scroll;
scroll-behavior: smooth; //使动画到达相应的位置的时候是顺滑的
}
.scroll-page {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
font-size: 5em;
}

\ \n \t

\表示转义字符
var a = "我说:"你好啊!""
console.log(a) //报错
var a = "我说:\"你好啊!\""
console.log(a) //"我说:"你好啊!""
\n换行
\t表示一个tab符

强制数据类型转换

强制转换成字符串,转换必须重新赋值,不改变原来的变量

强制转换成字符串,转换必须重新赋值,不改变原来的变量
1.用toString()方法
var a = 123;
console.log(typeof(a.toSrting()) //number
方法必须重新赋值,a可以重新赋值,最后得到的是最下面的一个a值
a = a.toString()
console.log(typeof(a.toSrting()) //string

2.用String()函数
var a = 123;
a = String(a);
console.log(typeof(a)) //srting

转换成number

1。Number() Number()只有函数没有方法
var a = '123';
console.log(Number(a)) //123
var a = '123sx';
console.log(Number(a)) //NaN
var a = null;
console.log(Number(a)) //0
var a = undefind
console.log(Number(a)) //NaN
var a = true
console.log(Number(a)) //1
var a = false
console.log(Number(a)) //0
2.parseInt(),parseFloat()只作用于字符串
var a = '123sx';
console.log(parseInt(a)) //123
var a = '123sx555';
console.log(parseInt(a)) //123
var a = '12.3sx555';
console.log(parseInt(a)) //12
var a = '12.3sx555';
console.log(parseFloat(a)) //12.3

转换成bolean

 数字    转换	除了0和nan其他的都是true
字符串 转换 除了‘’其他的都是true
null 转换 false
undefind 转换 false

测试一段代码用了多长时间

console.time('tast');
for (var i = 2; i <= 10; i++) {
var flag = true;
for (var j = 2; j < Math.sqrt(i); j++) {
if (i % j == 0) {
flag = false;
break;
}
}
if (flag) {
document.write(i);
}
}
console.timeEnd('tast'); //0.234444ms

对象

		/*
对象的取值 obj.name
当属性名是重新定义的变量的时候我们的用obj['属性名']来取属性值

查看是否在一个对象里有其属性名(属性名 in 对象) 返回true和false
*/
var obj = {
name: '你好',
age: 89,
['abg_sa']: 22,
};
var n = ['abg_sa'];
var b = age;
console.log(obj[n]); //22
console.log(obj.b); //age is not defined
console.log('age' in obj); //true
console.log('demault' in obj); //false

堆和栈

基本类型存储的时候他的变量名和值是存在栈中。

基本数据类型:当a的值赋值为123,然后把a赋值给b,当a的值变化的时候,b的值是不变的

但是当a的值赋给b的时候,并且a,b再都没变值的情况下a=b

image-20220324231428192

引用数据类型存储数据的时候栈中存储的是变量名和值所对应的地址,它的值在堆中会开辟一块空间,每一个new的对象在堆中开辟的空间都会有一个相对应的地址名存储在栈的值中。

引用数据类型:把obj对象赋值给obj1,然后obj里面的值变化的时候,obj1的值也会变化,因为他们都指向的是同一个堆内存只是对应的地址名不同。

obj != obj1:因为他们的值赋的是不同的地址名

image-20220324231942684

image-20220324232314073

image-20220324232635438

变量提升

var a = 123;
function fn() {
alert(a);
}
fn(); //123

var a = 123;
function fn() {
alert(a);
var a = 456;
}
fn(); //undefined
alert(a); //123

var a = 123;
function fn() {
alert(a);
a = 456;
}
fn(); //123
alert(a); //456

var a = 123;
function fn(a) {
alert(a);
a = 456;
}
fn(); //undefined
alert(a); //123

var a = 123;
function fn(a) {
alert(a);
a = 456;
}
fn(123); //123
alert(a); //123

一个对象是否是一个类的实例

dog instanceof person	//对象 instanceof 构造函数

原型对象

image-20220328134455874

/*
缺点:fn是全局函数会影响其他的地方
需求:既不是全局函数又可以在多个对象中可以用
方案:用当构造函数的时候会自动添加的一个属性prototype (给原型中添加)
*/
function Person(name, age) {
(this.name = name), (this.age = age), (this.sayname = fn);
}
function fn() {
console.log(`我的${this.name}`);
}
var obj1 = new Person('猪八戒', 23);
var obj2 = new Person('沙和尚', 13);
console.log(obj1);
obj1.sayname();
console.log(obj2);
obj2.sayname();

// 改进 :给这一类的prototype添加一个函数
function Person(name, age) {
(this.name = name), (this.age = age), (this.sayname = fn);
}
Person.prototype.fn = function () {
console.log(`我的${this.name}`);
};

var obj1 = new Person('猪八戒', 23);
var obj2 = new Person('沙和尚', 13);
console.log(obj1);
obj1.sayname();
console.log(obj2);
obj2.sayname();

数组

对原数组产生影响的有splice,reverse,sort

 /*
push 向数组末尾添加一个活多个元素

*/
var arr = [1, 2, 3, 4, 5];
console.log(arr.push('nihao', '汤汁')); //7
console.log(arr); //[1, 2, 3, 4, 5, 'nihao', '汤汁']

/*
pop 删除数组的最后一个元素
*/
console.log(arr.pop()); //汤汁
console.log(arr); //[1, 2, 3, 4, 5, 'nihao']

/*
unshift 向数组的最前面添加元素
*/
console.log(arr.unshift('前面', '测试')); //8
console.log(arr); //['前面', '测试', 1, 2, 3, 4, 5, 'nihao']
/*
shift 删除数组的第一个元素
*/
console.log(arr.shift()); //前面
console.log(arr); //['测试', 1, 2, 3, 4, 5, 'nihao']

/*
数组的遍历
*/
var arr = ['nihao', 2, 3, 4, 5];
for (item in arr) {
console.log(item); //0,1,2,3,4
console.log(arr[item]); //'nihao', 2, 3, 4, 5
}
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]); //'nihao', 2, 3, 4, 5
}
  /*
forEach forEach IE8以下的版本一般不支持
*/
var arr6 = [23, 45, 78, 88, 55, 44];
arr6.forEach((value, index, err) => {
console.log(value); //23, 45, 78, 88, 55, 44
console.log(index); //0,1,2,3,4,5
console.log(err); //[23, 45, 78, 88, 55, 44]
});
/*
slice() 截取元素 原数组不会变,重新定义新数组装所取的值
slice(2) slice传一个值的时候,表示从传入的值开始截取到结束,包括传入的index所对应的值
slice(2,3) slice传入两个值的时候,表示从第一个值开始截取(包含第一个下标index所对应的值)到第二个值对应的下标结束(不包括第二个值)
*/
var onearr = ['孙悟空', '沙和尚', '唐僧', '猪八戒'];
var lastarr = onearr.slice(2);
console.log(onearr); //['孙悟空', '沙和尚', '唐僧', '猪八戒']
console.log(lastarr); //['唐僧', '猪八戒']
var lastarr = onearr.slice(1, 3);
console.log(onearr); //['孙悟空', '沙和尚', '唐僧', '猪八戒']
console.log(lastarr); //['沙和尚', '唐僧']
  /*
splice() 删除元素,改变原来的数组,原来的数组是删除之后剩下的元素,新的是表示删除的元素
splice(2) 传入一个值的时候,则当作是一个值到最终,删除了从下标开始的元素一直到最后赋值给新的一个数组,原来数组就剩下了删除之后的元素
splice(3,1) 传入两个值的时候,表示从下标为3的元素开始(包含此元素)删除1个赋值给新元素,原数组就是删除之后剩下的元素
splice(3,1,333) 当传入三个值(或者更多)的时候,第一个值表示从那个元素开始,第二个元素表示删除几个,第三个元素(以后跟多的元素)替换删掉的位置
*/
var onearr = ['孙悟空', '沙和尚', '唐僧', '猪八戒'];
var lastarr = onearr.splice(2);
console.log(onearr); //['孙悟空', '沙和尚']
console.log(lastarr); //['唐僧', '猪八戒']
var lastarr = onearr.splice(1, 3);
console.log(onearr); //['孙悟空']
console.log(lastarr); // ['沙和尚', '唐僧', '猪八戒']
var lastarr = onearr.splice(3, 1);
console.log(onearr); //['孙悟空', '沙和尚', '唐僧']
console.log(lastarr); //['猪八戒']
var lastarr = onearr.splice(3, 1, 333);
console.log(onearr); // ['孙悟空', '沙和尚', '唐僧', 333]
console.log(lastarr); //['猪八戒']
/*
concat,数组的拼接,不会对原数组产生影响
*/
var arr = [2, 3, 4];
var arr1 = [9, 5, 6];
var arr2 = [0, 5, 4, 3];
var resut = arr.concat(arr1, arr2); //(10) [2, 3, 4, 9, 5, 6, 0, 5, 4, 3]
var resute = arr.concat(arr1, '拼接1', '拼接2', '....'); //(9) [2, 3, 4, 9, 5, 6, '拼接1', '拼接2', '....']
console.log(resut, resute);
/*
join 将数组转换成字符串
不会对原数组产生影响
*/
arr.join(); //默认以逗号连接
arr.join('-'); //以-连起来的字符串
/*
reverse()//翻转数组,会直接修改原数组
*/
var reversearr = [1, 2, 3, 4];
reversearr.reverse();
/*
sort 对数组里面的元素进行排序 影响原数组 对字母排序,纯数字元素排序也只能是十以内的数字可以正常排序
解决:自己指定排序规则,写一个回调函数
*/
var sortarr = [6, 3, 5, 7, 9, 11, 44, 99];
var resut = sortarr.sort((a, b) => {
/*
看返回值,如果说返回值是b-a则数组从大到小排序
返回值是a-b则从小到大排序
*/
return b - a; //(8) [99, 44, 11, 9, 7, 6, 5, 3]
return a - b; //(8) [3, 5, 6, 7, 9, 11, 44, 99]
});
console.log(resut);
console.log(sortarr);

for循环的数组去重

var arr = [1, 3, 3, 3, 3, 5, 3, 4, 4, 4, 4, 5, 3, 3, 3, 3, 6];
1.for (var i = 1; i < arr.length; i++) {
for (var j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
arr.splice(i, 1);
i--; //当当前的i删除之后,arr[i]会漏掉一个,所以我们把i又回退1,
}
}
console.log('总', arr);
}
console.log(arr); //[1, 3, 5, 4, 6]

2.for (var i = 0; i < arr.length; i++) {
for (j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
arr.splice(j, 1);
j--;
}
}
}
console.log(arr); //[1, 3, 5, 4, 6]

indexof去重

var str = '321990';
var newstr = [];
for (var i = 0; i < str.length; i++) {
if (newstr.indexOf(str[i]) == -1) {
newstr.push(str[i]);
}
}
console.log(newstr.toString()); //3,2,1,9,0

argument

/*
arguments
当我们调用函数的时候只有实参没有形参的时候,实参的值其实在arguments里面存储。
*/
function fun() {
console.log('实参');
console.log(arguments.length); //2
console.log(arguments[0]); //第一个参数
console.log(arguments[1]); //第二个参数
}
fun('第一个参数', '第二个参数');

Math

/*
Math.ceil()//向上取整
*/
console.log(Math.ceil(3.5)); //4
console.log(Math.ceil(3.2)); //4
/*
Math.floor()//向下取整
*/
console.log(Math.floor(3.5)); //3
console.log(Math.floor(3.2)); //3
/*
Math.round()//四舍五入xiang
*/
console.log(Math.round(3.5)); //4
console.log(Math.round(3.2)); //3
/*
Math.random()//0和1之间的随机数
随机生成x-y之间的随机数
Math.round(Math.random()*(y-x)+x)
*/
console.log(Math.round(Math.random() * (9 - 1) + 1));
/*
获取多个数中的最大值
*/
console.log(Math.min(22, 44, 1)); //1
/*
获取多个数中的最小值
*/
console.log(Math.max(22, 44, 1)); //44

字符串和正则相结合,split,search,match,replace

/*
字符串和正则配合的使用
spilt 用正则的规则已想要的方式分开字符串 默认匹配全局
search 搜索 返回第一次搜索到的下标 即使写了全局匹配也没有用,只能匹配一个
math 找出符合条件的内容提取出来 默认只匹配一次返回元素,设置全局就全部提取出来
replace 替换 默认只替换第一次找到的元素,设置全局就会全部替换
*/
var str = '1a2b3c4d5e6f7c2';
var result = str.split(/[a-z]/);
console.log(result); // ['1', '2', '3', '4', '5', '6', '7', '2']

var result1 = str.search(/c/);
console.log(result1); //5
var result1 = str.search(/c/g);
console.log(result1); //5

var result2 = str.match(/[a-z]/);
console.log(result2); //a
var result2 = str.match(/[a-z]/g);
console.log(result2); //['a', 'b', 'c', 'd', 'e', 'f', 'c']

var result3 = str.replace(/[a-z]/, '连接');
console.log(result3); //1连接2b3c4d5e6f7c2
var result3 = str.replace(/[a-z]/g, '连接');
console.log(result3); //1连接2连接3连接4连接5连接6连接7连接2

原生阻止事件冒泡事件

<div id="box">
<div id="innerbox"></div>
</div>
<script>
document.getElementById('box').onclick = function () {
alert('box');
};
document.getElementById('innerbox').onclick = function () {
alert('innerbox');
// 阻止事件冒泡
event.cancelBubble = true;
};
</script>

获取一个随机颜色

randomcolor() {
   for (var i = 0; i < this.list.length; i++) {
       // 随机组合成六个不同的颜色字母
       var sum = '';
       var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
       for (var j = 0; j < 6; j++) {
           var num = this.randoms(0, 15);
           sum = sum + arr[num];
      }
       this.list[i].background = '#' + sum;
  }
},
   // 随机生成背景色
   randoms(m, n) {
       return Math.floor(Math.random() * (n - m + 1)) + m;
  }

原生js切换classname和添加classname

<style>
  .b1 {
       width: 200px;
       height: 200px;
       background: red;
  }
.b2 {
   width: 300px;
   /* height: 300px; */
   background: green;
}
</style>

<button id="btn">点击</button>
<div class="b1" id="box"></div>

<script>
   window.onload = function () {
   var btn = document.getElementById('btn');
   var box = document.getElementById('box');
   btn.onclick = function () {
       box.className += ' b2'; //<div class="b1 b2" id="box"></div>
       box.className = 'b2' //<div class="b2" id="box"></div>
  };
};
</script>

给后端传值的时候,后端识别不到

前端 var obj = {name:'小王',age:16,address:'兰州市'}对象传到后端是不被后端所识别的,
后端可以识别json格式,json格式中属性名必须是带双引号的。
所以当后端不识别前端传过去的值的时候我们可以转成json格式
var str = JSON.stringify(obj)

面试

1。undefined与null的区别
undefined是定义了没有赋值
null是定义了并且赋值给null
2.什么时候赋值为null了
初始赋值为null表示后面将要赋值对象  var b = null
定义的函数或者数据释放空间,赋值给null是表示释放将不占空间(被垃圾回收器回收)
3.

 

posted on 2021-05-24 13:54  小仙女是不喝酒的  阅读(193)  评论(0)    收藏  举报