Web前端面试笔试题(二)
5.BOM模型
浏览器对象模型,可以对浏览器窗口进行访问和操作,使用BOM,开发者可以移动窗口,改变状态栏中的文本等与页面内容不相关的操作
Window对象
#FormatImgID_0#
这里可以用window.frames[0]或者用windows.frames[“topFrame”]来引用框架,也可以用topl来代替window属性。Top.frames[0] 。window对象可以忽略
提供的方法有moveto,moveBy,resizeTo,resizeBy等方法。但尽量避免使用它们,因为会对用户浏览产生影响
Open方法
#FormatImgID_1#
除了open方法,还有alert,comfirm,prompt方法
状态栏
#FormatImgID_2#
#FormatImgID_3#
Settimeout与setInterval
Settimeout
下面的代码都是在1秒钟后显示一条警告
Settimeout(“alert(‘aa’),1000”);
Settimeout(function(){alert(‘aa’);},1000);
如果要还未执行的暂停,可调用clearTimeOut()方法
Var si = Settimeout(function(){alert(‘aa’);},1000);
clearTimeout(si);
#FormatImgID_4#
setInterval
#FormatImgID_5#
History
向后一页window.history.go(-1); 等于history.back();
向前一页window.history.go(1); 等于 history.forword();
Document
LastModified,title,URL属性都是比较常用
#FormatImgID_6#
Location对象
Navigator对象
Screen对象
6.事件
6.1 冒泡型事件
function add(sText){
var oDiv = document.getElementById("display");
oDiv.innerHTML += sText; //输出点击顺序
}
Click Me
先执行最里面的p,再往外执行
6.2 监听函数
window.onload = function(){
var oP = document.getElementById("myP"); //找到对象
oP.onclick = function(){ //设置事件监听函数
alert('我被点击了');
}
}
Click Me
Function a(){}
oP.onclick = a
这样会先把a函数加载到缓存,不是最佳方案
Var A = Function(){}
oP.onclick = a
这样只有在onclick事件发生的时候,加载该函数
若以上的监听函数,在onclick的时候,需要执行多个函数,那就只能用以下的方法:
IE标准:
function fnClick(){
alert("我被点击了");
oP.detachEvent("onclick",fnClick); //点击了一次后删除监听函数
}
var oP;//声明在函数外,这样就可以两个函数一起使用
window.onload = function(){
oP = document.getElementById("myP"); //找到对象
oP.attachEvent("onclick",fnClick); //添加监听函数
}
Click Me
也可以添加多个监听器
oP.attachEvent("onclick",fnClick1); //添加监听函数1
oP.attachEvent("onclick",fnClick2); //添加监听函数2
执行顺序为fnClick2-> fnClick1
但是以上的监听器均为IE中的标准,而符合标准DOM(firefox)的监听器如下
oP.addEventListener("click",fnClick1,false); //添加监听函数1
oP.addEventListener("click",fnClick2,false); //添加监听函数2
因此这种方式在Firefox中支持,而在IE中不支持
为了兼容性,可这样写
if (el.addEventListener)...{
el.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent)...{
el.attachEvent('onclick', KindDisableMenu);
}
第三个参数为useCapture
#FormatImgID_7#
而useCapture這個參數就是在控制這時候兩個click事件的先後順序。如果是false,那就會使用bubbling,他是從內而外的流程,所以會先執行藍色元素的click事件再執行紅色元素的click事件,如果是true,那就是capture,和bubbling相反是由外而內
6.3 事件的类型 event.type
IE浏览器中事件对象是window对象的一个属性event
Op.onlick=function(){ var o = window.event}
而标准DOM中规定event对象必须作为唯一的参数传给事件处理函数
Op.onclick=function(oevent){
}
因此为了兼容两种浏览器,通常采用下面的方法
Op.onclick=function(o){
If(window.event)//假如不等于空,则为IE浏览器
O = window.event;
}
function handle(oEvent){
var oDiv = document.getElementById("display");
if(window.event) oEvent = window.event; //处理兼容性,获得事件对象
if(oEvent.type == "click") //检测事件名称
oDiv.innerHTML += "你点击了我 ";
else if( oEvent.type == "mouseover")
oDiv.innerHTML += "你移动到我上方了 ";
}
window.onload = function(){
var oImg = document.getElementsByTagName("img")[0];
oImg.onclick = handle;
oImg.onmouseover = handle;
}
还有很多鼠标事件
window.onload = function(){
var oImg = document.getElementsByTagName("img")[0];
oImg.onmousedown = handle; //将鼠标事件除了mousemove外都监听
oImg.onmouseup = handle;
oImg.onmouseover = handle;
oImg.onmouseout = handle;
oImg.onclick = handle;
oImg.ondblclick = handle;
}
6.4 事件的激活元素 event.srcElement 或者 target
function handle(oEvent){
if(window.event) oEvent = window.event; //处理兼容性,获得事件对象
var oTarget;
if(oEvent.srcElement) //处理兼容性,获取事件目标
oTarget = oEvent.srcElement; //IE支持的写法
else
oTarget = oEvent.target; //Firefox支持的写法
alert(oTarget.tagName); //弹出目标的标记名称
}
window.onload = function(){
var oImg = document.getElementsByTagName("img")[0];
oImg.onclick = handle;
}
event.button
function TestClick(oEvent){
var oDiv = document.getElementById("display");
if(window.event)
oEvent = window.event;
oDiv.innerHTML += oEvent.button; //输出button的值
}
document.onmousedown = TestClick;
window.onload = TestClick; //测试未按下任何键
在IE/Opera中,是window.event,而在Firefox中,是event
而事件的对象,在IE中是window.event.srcElement,在Firefox中是event.target,而在Opera中则两者都支持。
在 IE 里面
左键是 window.event.button = 1
右键是 window.event.button = 2
中键是 window.event.button = 4
没有按键动作的时候 window.event.button = 0
在 Firefox 里面
左键是 event.button = 0
右键是 event.button = 2
中键是 event.button = 1
没有按键动作的时候 event.button = 0
在 Opera 7.23/7.54 里面
鼠标左键是 window.event.button = 1
没有按键动作的时候 window.event.button = 1
右键和中键无法获取
键盘事件
window.onload = function(){
var oTextArea = document.getElementsByTagName("textarea")[0];
oTextArea.onkeydown = handle; //监听所有键盘事件
oTextArea.onkeyup = handle;
oTextArea.onkeypress = handle;
}
e.keyCode;
onkeypress是在用户按下并放开任何字母数字键时发生。系统按钮(例如,箭头键和功能键, Shift、Ctrl、Alt、F1、F2)无法得到识别。
onkeyup 是在用户放开任何先前按下的键盘键时发生。
onkeydown 是在用户按下任何键盘键(包括系统按钮,如箭头键和功能键)时发生
屏蔽鼠标右键
第一种方式:
function block(oEvent){
if(window.event)
oEvent = window.event;
if(oEvent.button == 2)
alert("鼠标右键不可用");
}
document.onmousedown = block;
第二种方式:
function block(oEvent){
if(window.event){
oEvent = window.event;
oEvent.returnValue = false; //取消默认事件 支持IE
}else
oEvent.preventDefault(); //取消默认事件 支持Firefox
}
document.oncontextmenu = block;
6.8伸缩的菜单
function change(){
//通过父元素li,找到兄弟元素ul
var oSecondDiv = this.parentNode.getElementsByTagName("ul")[0];//这里的this就是下面的OA
//CSS交替更换来实现显、隐
if(oSecondDiv.className == "myHide")
oSecondDiv.className = "myShow";
else
oSecondDiv.className = "myHide";
}
window.onload = function(){
var oUl = document.getElementById("listUL");
var aLi = oUl.childNodes; //子元素
var oA;
for(var i=0;i //如果子元素为li,且这个li有子菜单ul if(aLi[i].tagName == "LI" && aLi[i].getElementsByTagName("ul").length){ oA = aLi[i].firstChild; //找到超链接 oA.onclick = change; //动态添加点击函数 } } } tagName出来的都是大写 总结 《Event详解》 DOM常用属性 tagName nodeValue nodeName nodeType parentNode childNodes firstChild lastChild nextSibling (IE) previousSibling (IE) attributes innerHTML style className 方法 getElementById getElementsByName getElementsByTagName hasChildNodes() getAttribute setAttribute createElement createTextNode appendChild removeChild replaceChild insertBefore cloneNode createDocumentFragment detachEvent attachEvent(IE) addEventListener(DOM) event属性 type keyCode srcElement(IE) target(DOM) button 鼠标事件 onclick onmouseover onmousedown onmouseup onmouseout ondblclick 键盘事件 onkeydown onkeyup onkeypress window事件 onload document事件 oncontextmenu write onmousedown 7.JavaScipt优化和调试 7.1 错误和异常 拼写错误、访问不存在的变量,括号不匹配,等号与赋值 声明变量时,要记住局部变量和全局变量的区别 Function square(num){ Total = num*num; Return total; } Var total = 50; Var number = Square(20); Alert(total); 这些代码将不可避免地导致全局变量total的值发生变化。 Function square(num){ Var Total = num*num; Return total; } 7.2 错误处理 onerror
window.onerror = function(){
alert("出错啦!");
return true; //屏蔽系统事件
}
Try..catch
try{
alert("this is an example");
alert(fresheggs);
} catch(exception){
var sError = "";
for(var i in exception)
sError += i + ":" + exception[i] + " ";
alert(sError);
}
7.3 调试器
IE-工具-Intenet选项-高级->禁用调试,显示脚本错误
Firefox错误控制台
Microsoft script debugger
Venkman firefox的插件
6.4 JavaScript优化
1.提高JavaScript下载时间。将JavaScript写到同一行
2.尽量使用内置函数(因为内置函数是通过C语言编译到浏览器中的)
.实例
1 图片查看器
function showPic(obj){
var h = obj.getAttribute("href");
document.getElementById("image").setAttribute("src",h);
}
Snapshots

Return false指的是把默认的noclick事件取消
给其加上css
body{
color:#333;
background:#ccc;
margin:1em 10%;
}
a{
text-decoration:none;
padding:10px;
color:#c60;
}
a:link, a:visited{
color: #A62020; background-color: #ecd8db; text-decoration: none; padding:4px 10px 4px 10px;
border-top:1px solid #EEE;
border-left:1px solid #EEE;
border-bottom:1px solid #717171;
border-right:1px solid #717171;
}
a:hover{
color:#821818; background-color:#e2c4c9; padding:5px 8px 3px 12px;
border-top:1px solid #717171;
border-left:1px solid #717171;
border-bottom:1px solid #EEE;
border-right:1px solid #EEE;}
ul{
margin:0px;
padding:0px;
}
li{
list-style-type:none;
display:inline;
}
img{
margin:10px 0px;
}
当时现在有个缺陷,就是onclick的事件直接写在了HTML上,分离
先给ul加上个属性id
window.onload = prepareGalley;
function prepareGalley(){
var img_ul = document.getElementById("img_ul");
var links = img_ul.getElementsByTagName("a");
for(var i=0;i links[i].onclick = function(){ showPic(this); return false; } } } 有一个问题,如果onload的函数有多个怎么办? window.onload = prepareGalley1; window.onload = prepareGalley2; 显然,这样第一个函数就会被第二个函数覆盖。 可以这样写 Window.onload = function(){ prepareGalley1(); prepareGalley2(); } 还有一个比这个更NB的写法,由Simon Willison写的 function addLoadEvent(func){ var oldonload = window.onload; if(typeof window.onload !='function'){ window.onload = func; }else{ window.onload = function(){ oldonload(); func(); } } } addLoadEvent(prepareGalley1); addLoadEvent(prepareGalley2); 编写一个方法 求一个字符串的字节长度 new function(s){ if(!arguments.length||!s) return null; if(""==s) return 0; var l=0; for(var i=0;i if(s.charCodeAt(i)>255) l+=2; else l++; } alert(l); }("hello world!"); 如何控制alert中的换行 alert("hello world"); 解释document.getElementById("ElementID").style.fontSize="1.5em" 设置id为ElementID的元素的字体大小为1.5个相对单位 Em为相对长度单位。相对于当前对象内文本的字体尺寸。 如当前对行内文本的字体尺寸未被人为设置,则相对于浏览器的默认字体尺寸。 1em=16px 按照格式 xxxx年xx月xx日xx时xx分xx秒动态显示时间 要求不足10的补0 function tick(){ var d=new Date(); var t=function(a){return a<10?"0"+a:a;} Clock.innerHTML=d.getFullYear()+"年"+t(d.getMonth()+1)+"月"+t(d.getDate())+"日"+t(d.getHours())+"时" +t(d.getMinutes())+"分"+t(d.getSeconds())+"秒"; window.setTimeout("tick()",1000); } window.onload=tick;
编写一个方法 去掉一个数组的重复元素
Array.prototype.strip=function(){
if(this.length<2) return [this[0]]||[];
var arr=[];
for(var i=0;i arr.push(this.splice(i--,1));//将本数组中第一个元素取出放入到数组arr中 for(var j=0;j if(this[j]==arr[arr.length-1]){ this.splice(j--,1);//删除本数组中与数组arr中最后一个元素相同的元素 } } } return arr; } var arr=["abc",85,"abc",85,8,8,1,2,5,4,7,8]; alert(arr.strip()); 说出3条以上ff和ie的脚本兼容问题 IE有children,FF没有; IE有parentElement,FF没有; IE有 innerText,outerText,outerHTML,FF没有; IE有数据岛,FF没有; FF有 HTMLElement,HTMLDivElement,XMLDocument,DocumentFragment,Node,Event,Element 等等,IE没有; IE跟FF创建HttpRequest实例的方法不一样 DIV中border、margin和padding的区别和用法 边框属性(border)用来设定一个元素的边线 外边距属性(margin)是用来设置一个元素所占空间的边缘到相邻元素之间的距离 内边距属性(padding)是用来设置元素内容到元素边界的距离 为Array写一个indexof方法 Array.prototype.indexOf = function(e){ for(var i=0,j; j=this[i]; i++){ if(j==e){return i;} } return -1; } Array.prototype.lastIndexOf = function(e){ for(var i=this.length-1,j; j=this[i]; i--){ if(j==e){return i;} } return -1; } var arr=[1,2,3,4,5]; alert(arr.indexOf(5)); 克隆 浅复制(影子克隆):只复制对象的基本类型,对象类型,仍属于原来的引用 深复制(深度克隆):不紧复制对象的基本类,同时也复制原对象中的对象.就是说完全是新对象产生的 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 ( typeof(this[key]) == 'object' ){ objClone[key] = this[key].Clone(); }else{ objClone[key] = this[key]; } } } objClone.toString = this.toString; objClone.valueOf = this.valueOf; return objClone; } 兼容 IE 和 FF 的换行 CSS 推荐样式 word-wrap:break-word; overflow:hidden; word-wrap是控制换行的。使用break-word时,是将强制换行。中文没有任何问题,英文语句也没问题。但是对于长串的英文,就不起作用。 word-break是控制是否断词的。 normal是默认情况,英文单词不被拆开。 break-all,是断开单词。在单词到边界时,下个字母自动到下一行。主要解决了长串英文的问题。 keep-all,是指Chinese, Japanese, and Korean不断词。即只用此时,不用word-wrap,中文就不会换行了。(英文语句正常。) 手型Cursor的兼容IE和FF写法 cursor:pointer alt作为图片的替代文字出现,title是图片的解释文字 图片存在 只有alt 图片的解释文字 只有title 图片的解释文字 两者都有 图片的解释文字 两者都没有 图片既没有替代文字,也没有解释文字 图片不存在 只有alt 图片既有替代文字,又有解释文字 只有title 图片没有替代文字,只有解释文字 两者都有 图片既有替代文字,又有解释文字 两者都没有 图片既没有替代文字,也没有解释文字 当然不同的浏览器处理方式也会不一样 border-color-left、marin-left、-moz-viewport改写成JavaScript格式 border-color-left:borderLeftColor marin-left:marinLeft -moz-viewport:MozViewport 用css、html编写一个两列布局的网页,要求右侧宽度为200px,左侧自动扩展。 CSS: #right{ float:right; width:200px; } #left{ marin-right:200px; } HTML:元素的alt和title有什么异同?
Linux题目:批量删除当前目录下后缀名为.c的文件,如a.c、b.c
rm *.c
如何提高网页的运行速度
内容与形式分离,模块化开发,优化CSS
减少页面文档大小
尽量减少图片的使用或注意图片的大小,优化图片:格式、质量、图片长宽标志
减少响应的次数,用Ajax
网址后面加一个“/”
按要求写一个简单的ajax示例
var Browser={/**Browser对象用于检测浏览器,其中用到了IE的条件编译*/
isFF:window.navigator.appName.toUpperCase().indexOf("NETSCAPE")!=-1?true:false,
isOpera:window.navigator.appName.toUpperCase().indexOf("OPERA")!=-1?true:false
};
Function.prototype.bind=function(object){
var _this=this;
return function(){
_this.apply(object,arguments);
}
}
function HttpRequest(){
this.async=true;
this.cache=false;
this.xmlhttp=function(){
if(Browser.isFF&&window.XMLHttpRequest){
try{
return new XMLHttpRequest();
}catch(e){}
}else if(Browser.isIE&&window.ActiveXObject){
var Version = ["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.5.0","Msxml2.XMLHTTP.4.0","Msxml2.XMLHTTP.3.0",+
"Msxml2.XMLHTTP.2.6","Msxml2.XMLHTTP","Microsoft.XMLHTTP.1.0","Microsoft.XMLHTTP.1","Microsoft.XMLHTTP"];
for(var i=0;i try{ return new ActiveXObject(Version[i]); }catch(e){} } } }()||false; }HttpRequest.prototype={ send:function(object,url,callback){ if(!this.xmlhttp) return; this.xmlhttp.open(object?"post":"get",url,!!this.async); if(object) this.xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded"); if(!this.cache){ this.xmlhttp.setRequestHeader("No-Cache","1"); this.xmlhttp.setRequestHeader("Pragma","no-cache"); this.xmlhttp.setRequestHeader("Cache-Control","no-cache"); this.xmlhttp.setRequestHeader("Expire","0"); this.xmlhttp.setRequestHeader("Last-Modified","Wed, 1 Jan 1997 00:00:00 GMT"); this.xmlhttp.setRequestHeader("If-Modified-Since","-1"); } if(!this.callback) this.callback=callback; if(!this.async){ if(typeof(this.callback)=="string"){ eval(this.callback); }else if(typeof(this.callback)=="function"){ this.callback(this.xmlhttp); } }else{ this.xmlhttp.onreadystatechange=function(){ if(this.xmlhttp.readyState==4){ if(this.xmlhttp.status==0||this.xmlhttp.status==200){ if(typeof(this.callback)=="string"){ eval(this.callback); }else if(typeof(this.callback)=="function"){ this.callback(this.xmlhttp); } } } }.bind(this); } this.xmlhttp.send(object); },abort:function(){ if(this.xmlhttp&&this.xmlhttp.abort) this.xmlhttp.abort(); } }; //ajax类定义结束 new HttpRequest().send(null,"http://bbs.51js.com/index.php",function(r){ document.getElementById("load").innerHTML=r.responseText.match(/