HTML+CSS
1、如何实现不确定宽高的盒子上下左右居中
c3的属性,移动自己大小的一半
div{
position:absolute;
top:50%; //相对于父元素
left:50%; //相对于父元素
transform:translate(-50%,-50%); //相对于自己
}
2、如何实现不确定宽高的图片上下左右居中
img{
position:absolute;
top:0; /* 四周拉力相同 */
right:0; /* 四周拉力相同 */
bottom:0; /* 四周拉力相同 */
left:0; /* 四周拉力相同 */
margin:auto; /* 再设置 marign 自动 */
}
3、纯css写倒三角的原理:
.kailong{
width:0;
height:0;
border-right:50px solid transparent;
border-left:50px solid transparent;
border-bottom:50px solid red;
}
4、前后端通信
浏览器的同源政策限制:端口,域名,协议 ,只要一个不一样就跨域
前后端如何通信:
Ajax
Websocket : 协议 http https (SSL) file socket.io
CORS fetch()
原生ajax实现:
function ajax(options){
var pramas = {
url:'',
type: 'get',
data: {},
success: function (data) {},
error: function (err) {},
}
options = Object.assign(pramas, options)
if(options.url){
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")
var url = options.url,
type = options.type.toUpperCase(),
data = options.data,
dataArr = [];
for(let key in data){
let value = key + '='+ data[key]
dataArr.push(value)
}
if(type === "GET"){
url = url + "?" + dataArr.join('&')
xhr.open(type, url, true)
xhr.send()
}
if(type === "POST"){
xhr.open(type,url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
xhr.send(dataArr.join('&'))
}
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) { // 304未修改
options.success(xhr.responseText)
}else {
options.error(xhr.responseText)
}
}
}
}
跨域通信的几种方式:
JSONP: 通过script标签引入的js是不受同源策略的限制,得和后端订好那个字段是回调函数
postMessage
// postMessage
// 窗口A(http:A.com)向跨域的窗口B(http:B.com)发送信息
Bwindow.postMessage('data', 'http://B.com');
// 在窗口B中监听
Awindow.addEventListener('message', function (event) {
console.log(event.origin);
console.log(event.source);
console.log(event.data);
}, false);
Websocket
var ws = new WebSocket('wss://echo.websocket.org');
ws.onopen = function (evt) {
console.log('Connection open ...');
ws.send('Hello WebSockets!');
};
ws.onmessage = function (evt) {
console.log('Received Message: ', evt.data);
ws.close();
};
ws.onclose = function (evt) {
console.log('Connection closed.');
};
CORS: 通过配置fetch跨域(浏览器会拦截跨域请求,在请求头上添加跨域)
fetch('/some/url/', {
method: 'get',
}).then(function (response) {
}).catch(function (err) {
// 出错了,等价于 then 的第二个参数,但这样更好用更直观
});