前端面试题准备 1

亲戚推荐的前端面试还没消息,还是要准备一下,万一下周某一天突然要去面试,好歹不要露怯。这几天看前端面试题,大概有几个是必考的

一、原生js写ajax,平时用jquery的ajax习惯了,原生的没写过,网上找了一篇比较精练的

function CreateAjaxObj(){
    var xmlHttpRequest = null;
    if(window.XMLHttpRequest) xmlHttpRequest = new XMLHttpRequest();
    else if(window.ActiveXObject) xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    return xmlHttpRequest;
}
function Ajax(url,postStr,callback){
    var xmlHttpRequest = CreateAjaxObj();
    if(xmlHttpRequest != null){
        xmlHttpRequest.open("POST",url,true);
        xmlHttpRequest.onreadystatechange = function(){
            if(xmlHttpRequest.readystate == 4 && xmlHttpRequest.status == 200){
                callback(xmlHttpRequest.responseText);
            }
        };
        xmlHttpRequest.send(postStr);
    }
}

 试着手敲了几遍,大概记着了。

 

二、深复制(克隆),项目里正在用的好像没什么问题,没怎么测过,也是网上复制来的

function clone(myObj){
    if(typeof(myObj) != 'object') return myObj;
    if(myObj == null) return myObj;
    var myNewObj = new Object();
    for(var i in myObj) myNewObj[i] = clone(myObj[i]);
    return myNewObj;
}

不知是否严谨,今天在网上又找了一篇:

Object.prototype.Clone=function(){
    var objClone;
    if(this.constructor==Object){
        objClone=new this.constructor();
    }
    else{
        objClone=new this.constructor(this.valueOf());
    }
    for(var key in this){
        if(objClone[key]!=this[key]){
            if(objClone(this[key])=="object"){
                objClone[key]=this[key].clone();
            }
            else{
                objClone[key]=this[key];
            }
        }
    }
    objClone.toString=this.toString;
    objClone.valueOf=this.valueOf;
    return objClone;
}

能记住复杂的最好,记不住的话简略版的也要能手写的出来。

三、垂直居中,这也在项目中被坑过几次,今天试了一下,大概有几种方法,凭印象写个大概,具体还要调试:

1、一般用于图片在DIV中垂直居中,在图片旁边放个空元素,display:inline-block;0;height:100%,vertical-align:middle;

2、一般用于文字居中,把line-height设成父DIV的height一样。

3、DIV嵌DIV,父DIV display:table,子DIV display:table-cell,vertical-align:middle

4、知道宽高后直接偏移值,有时在项目中这样也很省事。。。

四、DIV页面固定位置(右下角广告位或居中),主要是要记得减去DIV本身的一半宽和高,(语法是个大概,具体怎么写还要试下)

1、CSS的position:fixed

2、如果页面不滚动的话position:abosulte也可以

3、用JS方法,$(window.height())-自身高度一半,(或是document?不记得了,可以试下) 

五、CSS选择符优先级

!important 最高
html直接定义 1000
ID选择器 100
标签名选择器 1
类选择器 10

六、ajax跨域

1、jquery的getJSON,或ajax的dataType设为'jsonp',或getScript。总之是利用JSONP

2、原生JS,可以生成标签,利用<script src="">后带参数来跨域

var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open("get", "script.js", true);
xhr.onreadystatechange = function() {    
  if (xhr.readyState == 4) {        
    if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304)
      {            
          var script = document.createElement ("script");            
          script.type = "text/javascript";            
          script.text = xhr.responseText;            
          document.body.appendChild(script);        
        }    
    }
};
xhr.send(null);

利用ajax动态加载js

七、清除浮动

1.增加个空标签 clear:both
2.overflow:auto
3. :afert伪类(非IE)