文章目录
前言
记录一下工作,学习中遇到的前端开发的问题~ ~ 不定期更新
一、H5开发
1.vscode使用live server
1.插件直接搜索live server安装

2.设置setting.json
"liveServer.settings.donotShowInfoMsg": true,
"liveServer.settings.port": 9000, //设置本地服务的端口号
"liveServer.settings.host": "localhost",//主机名配置,默认127.0.0.1
"liveServer.settings.root": "/", //设置根目录,也就是打开的文件会在该目录下找
"liveServer.settings.CustomBrowser": "chrome", //设置默认打开的浏览器
"liveServer.settings.NoBrowser": false,
"liveServer.settings.ChromeDebuggingAttachment": false,//启用Chrome调试到Live Server的附件
"liveServer.settings.fullReload": false,
"liveServer.settings.AdvanceCustomBrowserCmdLine": "",
"settingsSync.ignoredExtensions": [], //默认情况下,Live Server会在不完全重新加载浏览器的情况下注入CSS更改。您可以通过将此设置设置为来更改此行为true,默认false
"liveServer.settings.proxy": { //代理设置
"enable": true, //是否开启代理设置
"baseUri": "/api", //代理的访问根路径
"proxyUri": "http://127.0.0.1:9060" //远程服务端接口
}
3.启动live server
(1)右键点击html文件 Open with Live Server启动
(2)vscode 右下角点击Go live 启动

2. a标签html内跳转
// id标记
<div id="image"></div>
<a href="#image"/>
3.H5引入vue.js,双向绑定时,展示{{XXX}}问题
1.使用 v-text
<div class="news_name" v-text="title">
2.使用 v-cloak
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14"></script>
<style>
/* 加载完毕后显示 */
[v-cloak] {
display: none !important;
}
</style>
</head>
<body>
<div class="news_name" v-cloak>
{{itle}}
</div>
<!-- 自定义js,使用vue -->
<script src="index.js"></script>
</body>
</html>
亲测第一种有效;第二种仍有{{xxx}}问题,可能是我使用方式不对,欢迎探讨。
4. embed 标签
embed 中可以插入各种多媒体,此处用于放入PDF
<embed src="static/api/广告收益数据.pdf" type="application/pdf" width="100%" height="1000px">
二、css样式
1.设置属性保持同一水平
<style>
name: {
/* 保持同一水平线 */
vertical-align: middle;
}
</style>
// 设置超链接样式
a{
text-decoration: none;
color: inherit;
cursor: pointer;
}
2. css实现图片堆叠
<body>
<div id="app">
<div class="reward">
<div class="image1"></div>
</div>
<div class="reward">
<div class="image2"></div>
</div>
<div class="reward" >
<div class="image3"></div>
</div>
</div>
</body>
<style>
.image1{
width: 300px;
height: 300px;
background-color: tomato;
}
.image2{
width: 200px;
height: 200px;
background-color: springgreen;
}
.image3{
width: 100px;
height: 100px;
background-color: gold;
}
</style>
</html>

3. inline-flex下 标签居右展示
<div class="reward">
<div class="word_title">我是文字</div>
<button class="reward_button ">我是按钮</button>
</div>
<style>
.reward {
display: inline-flex;
width: 100%;
height: 100px;
}
.reward_button {
// 右对齐,左边距间隔设为自动
margin: 0px 20px 0px auto;
}
</style>

4. 单独设置子节点属性


.img_hammer:nth-child(1){
left: 65;
}
.img_hammer:nth-child(2){
left: 178;
}
.img_hammer:nth-child(3){
left: 300;
}
5. css导入字体包
/*导入字体包 */
@font-face {
font-family: Carattere-Regular;
src: url(Carattere-Regular.ttf);
}
#app {
display: block;
font-family: Carattere-Regular;
}
5. css样式始终居中
.content{
max-width: 24rem;
margin: 0px auto; // 重点在于左右间距自适应
}
6. 隐藏行数据
.text{
// 控制文本在容器中的行数,最多展示几行
-webkit-line-clamp: 2;
// 超出隐藏
overflow: hidden;
display: -webkit-box;
// CSS样式属性,它表示盒子的排列方式。vertical表示纵向排列,主要用于多行文本的排列。
-webkit-box-orient: vertical;
}
7. p标签强制换行
p{
word-break: break-all;
}
三、js
1. js.replace()
'1111222'.replace(/1/, '3') // "3111222"
// 带g为全局替换,否则只替换第一个
'1111222'.replace(/1/g, '3') // "3333222"
'1111哈哈哈啊'.replace(/哈哈/, '3') // "11113哈啊"
2. js.sort()
// 倒序
this.list.sort((a, b) => {
return b.day - a.day
})
// 倒序后再次倒序
this.list.sort((a, b) => {
const day = b.day - a.day
if (day !== 0) {
return day
}
return b.hour - a.hour
})
3. 获取url参数
// 取url问号后参数
getQueryString(name) {
var temp = window.location.href.split('?')[1];
var pram = new URLSearchParams('?'+temp);
return pram.get(name);
}
扩展 window.location.
| window.location.href | 属性返回当前页面的 URL |
4. JSON.parse()与JSON.stringify()
(1) 深拷贝
JSON.parse(JSON.stringify(**))
(2) stringify()
将一个 JavaScript 对象或值转换为 JSON 字符串
/**
* value JavaScript对象
* space 指定缩进
*/
JSON.stringify(value[, replacer [, space]])
例: JSON.stringify(exportData, undefined, 2)
参考文档: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON
5. toFixed()
// toFixed() 保留小数点后几位
33.66666.toFixed(2) // 34.67
33.2222.toFixed(3) // 33.22
5. XMLHttpRequest
XMLHttpRequest (简称 xhr )是浏览器提供的 Javascript 对象,可以请求服务器上的数据资源。
<script>
var text = ''
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url, true);
httpRequest.send();
httpRequest.onreadystatechange = function(){
/**
0:请求未初始化(还没有调用 open())。
1:请求已经建立,但是还没有发送(还没有调用 send())。
2:请求已发送,正在处理中(通常现在可以从响应中获取内容头)。
3:请求在处理中;通常响应中已有部分数据可用了,但是服务器还没有完成响应的生成。
4:响应已完成;您可以获取并使用服务器的响应了
*/
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
text = httpRequest.responseText
setTimeout(() => {
// 复制到剪贴板,移动端根据浏览器及权限原因,暂不能成功
navigator.clipboard.writeText(text).then(() => {
alert("成功")
}).catch(err => {
alert("失败")
})
}, 1000);
}
</script>
6. js执行动画效果
// 获取节点
const hammer = document.getElementsByClassName('img_hammer')[index]
// animate([]) 中设置动画效果
hammer.animate([{ transform: 'rotate(10deg)' }, { transform: 'rotate(0deg)' }, { transform: 'rotate(-10deg)' }, { transform: 'rotate(0deg)' }, { transform: 'rotate(10deg)' },], 1000);
7. js下载简单文件
downloadEvt(url, fileName) {
const el = document.createElement('a')
el.style.display = 'none'
el.setAttribute('target', '_blank')
/**
* download的属性是HTML5新增的属性
* href属性的地址必须是非跨域的地址,如果引用的是第三方的网站或者说是前后端分离的项目(调用后台的接口),这时download就会不起作用。
* 此时,如果是下载浏览器无法解析的文件,例如.exe,.xlsx..那么浏览器会自动下载,但是如果使用浏览器可以解析的文件,比如.txt,.png,.pdf....浏览器就会采取预览模式
* 所以,对于.txt,.png,.pdf等的预览功能我们就可以直接不设置download属性(前提是后端响应头的Content-Type: application/octet-stream,如果为application/pdf浏览器则会判断文件为 pdf ,自动执行预览的策略)
*/
fileName && el.setAttribute('download', fileName)
el.href = url
document.body.appendChild(el)
el.click()
document.body.removeChild(el)
}
8. canvas转为blob
canvas(){
const image = new Image()
image.src = '图片的url'
// 创建canvas
var mycanvas = document.createElement('canvas')
var myctx = mycanvas.getContext('2d')
image.onload = () => {
mycanvas.width = 1080
mycanvas.height = 1044
myctx.drawImage(image, 0, 0, 1080, 1044)
myctx.font = '72px Carattere-Regular'
myctx.fillStyle = '#FFFFFF'
myctx.fillText('写入的文字', 100, 100)
// 转为blob类型
const blob = this.dataURLToBlob(mycanvas.toDataURL('image/png'))
// 转化为File文件
const file = new window.File([blob], 'background.jpg')
}
}
dataURLToBlob(dataurl) {
const arr = dataurl.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], {
type: mime
})
},
9. js获取某个元素高度,并且隐藏多余行
// 通过.offsetHeight获取的高度与实际高度不一致
// 必须等到页面加载完毕之后才能正确获取content的高度,所以在onload 的方法里获取content高度才是实际的高度
<body id="body" onload="queryHeight()">
<div class="content">
// 内容
</div>
<script>
function queryHeight() {
// class元素有多个情况下,获取第一个
const content = document.getElementsByClassName('content')[0]
contentHeight = content.offsetHeight
if(content.offsetHeight > 800){
// 重新为元素样式赋值,隐藏多余行
content.style.height = 800
content.style.overflow = 'hidden'
}
}
</script>
</body>
10. iframe父子通信
父页面向子页面发送消息
// 父页面
<div>
<iframe id="iframe1" width="100%" height="100%" frameborder="0" scrolling="no" src="iframe.html"></iframe>
</div>
<script>
// send message to children
const iframe = document.getElementById('iframe1')
iframe.onload = function(){
// iframe.contentWindow.postMessage(send to children message, 'iframe page href');
iframe.contentWindow.postMessage(window.location.href, 'iframe页地址,需要全路径');
}
</script>
// 子页面
<script>
// listen message from children
window.addEventListener('message', e => {
console.log(e)
if (e.data.match('game/')) {
console.log('listen parent message', e)
this.parentUrl = e.data
}
}, false)
</script>
子页面向父页面发送消息
<script>
// 子页面
window.parent.postMessage('子页面发送的消息','父页面链接:http://a.index.com')
</script>
<script>
// 父页面
window.addEventListener('message',e=>{
// 对消息来源origin做一下过滤,避免接收到非法域名的消息导致的xss攻击
if(e.origin==='http://b.index.com'){
console.log(e.origin) //子页面URL,这里是http://b.index.com
console.log(e.source) // 子页面window对象,全等于iframe.contentWindow
console.log(e.data) //子页面发送的消息
}
}, false)
</script>
11.刷新当前页面
window.location.href = window.location.href
window.location.Reload()
区别在于是否有提交数据。当有提交数据时,window.location.Reload()会提示是否提交,window.location.href=window.location.href,则是向指定的url提交数据
12. vue-引入框架后跳转至固定页
new Vue({
el: '#app',
router,
store,
i18n,
created() {
// watch 路由的参数,以便再次获取数据
this.$watch(() => this.$route.params,
() => {
// console.log(this.$route)
const path = this.$route.path
if (path === '/home') {
this.$router.push({ path: '/data' })
}
},
// 组件创建完后获取数据,此时 data 已经被 observed 了
{ immediate: true }
)
},
render: h => h(App)
})
12. 获取固定范围内的随机数
function getRandom(list) {
if (list) {
// 随机获取集合内一个对象
const index = Math.floor(Math.random() * list.length)
return list[index - 1]
} else {
// 获取100内的随机数
return Math.floor(Math.random() * 100)
}
}
12. 按权重随机
// 按权重随机
// 转换权重
const list = [
{ rate: 30 },
{ rate: 30 },
{ rate: 40 },
]
// 思路:将比率相加,转换为权重值
var widget = 0
for (let index = 0; index < list.length; index++) {
var current = list[index]
var rate = current.rate
if (index === 0) {
widget = rate
current.widget = rate
} else {
widget += rate
current.widget = widget
}
}
const value = Math.floor(Math.random() * 100)
// 检查随机数,获取第一个大于随机数的权重值
var link = null
for (let index = 0; index < list.length; index++) {
const element = list[index];
if (element.widget > value) {
link = element
break
}
}
获取上月第一天和最后一天
queryLastMonthTime() {
const date = new Date()
let year = date.getFullYear()
// 当前月
const current_month = date.getMonth()
// 当前月第一天
const current_firstDay = new Date(year, current_month, 1)
// 上月最后一天
const last_lastDay = new Date(current_firstDay.getTime() - 1000 * 60 * 60 * 24)
// console.log(last_lastDay.getMonth(), last_lastDay.getDate())
let last_month = date.getMonth() - 1
if (last_month < 0) {
// 1月重新赋值
year -= 1
last_month = 11
}
// 上月第一天
const last_firstDay = new Date(year, last_month, 1)
// console.log(last_firstDay.getMonth(), last_firstDay.getDate())
return [last_firstDay.getTime(), last_lastDay.getTime()]
}
四、el-element
el-table 表头对齐
el-table
setTimeout(() => {
// 表头对齐
this.$refs.tables.doLayout()
}, 1200)
.el-table th.gutter{
display: table-cell!important;
}
本文档整理了前端开发中的H5、CSS样式和JavaScript常见问题与解决方案,包括VSCode的liveserver配置、Vue.js的双向绑定、CSS图片堆叠、js操作、XMLHttpRequest、canvas和iframe的使用等。同时,还介绍了Element UI中el-table的对齐方法。

1445

被折叠的 条评论
为什么被折叠?



