紧接着上 博客《BOM 常用API》的内容,且为了熟悉和了解BOM的API,我们来做一个BOM的库
主要功能,能在屏幕中间打开指定 URL,能读取或设置 location.search等
1.打开一个新窗口
1.1需求
封装window.open,调整中心坐标
1.2具体实现
window.$ = function () {
let array = [];
return array;
}
$.bom = {
//弹出居中窗口
openAtCenter: function (width, height, url) {
window.open(url, '_blank',
`width=${width}px,
height=${height}px,
screenX=${screen.width / 2 - width / 2}px,
screenY=${screen.height / 2 - height / 2}px`
);
}
}
2.修改查询参数
2.1需求
能输入一下代码进行查询
$.bomm.search('a');
$.bomm.search('a','xxx');
2.2具体实现
步骤:
- 首先去除无用的字符串
- 将获得得字符串再拆成对象,形成键值对已便操作
- 检测url,防止url有汉字
- 最后设置value
//查询字符串
search: function(name, value){
let searchAll = function(){
let result = {}
let search = window.location.search
// 去掉?
if(search[0] === '?'){
search = search.slice(1)
}
// 用 & 分隔成数组
let searchArray = search.split('&')
for(var i =0;i<searchArray.length; i++){
//再次分割url
let parts = searchArray[i].split('=')
// URI 进行解码变成中文
result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1] || '')
}
return result
}
let result = searchAll()
if(value === undefined){
return result[name]
}else{
if(result[name] === undefined){
location.search += `&${encodeURIComponent(name)}=${encodeURIComponent(value)}`
}else{
result[name] = encodeURIComponent(value)
let newSearch = '?'
for(let key in result){
newSearch += `${encodeURIComponent(key)}=${encodeURIComponent(result[key])}&`
}
location.search = newSearch
}
}
},
测试
预览:https://tazbingor.github.io/wheels/mybom/index.html
源码:https://github.com/tazbingor/wheels/blob/master/mybom/myBom.js
网友评论