做几道知乎看来的笔试题

知乎上一个哥们问的 我做一下顺便巩固一下知识 觉得题目还不错 问答式的写在前面  代码的统一写在后面

原题目地址http://www.zhihu.com/question/19863532

1.事件对象在IE与FF中有哪几个共同的属性呢?

坑爹的一道题 查文档查半天
altKey, ctrlKey, shiftKey button,clientX, clientY,type
没什么价值的一道题,但是事件对象模型一定要搞清楚 过几天会总结一下

2.IE的innerHTML需要注意哪些问题?

ie下一些元素的innerhtml的属性是只读的,不能赋值

3.请指出slice,substr,substring的不同

这个没查资料 完全自己回答的。。
都是字符串截取的方法 slice和substring差不多
用法a.slice(start,end) a.substring(start,end) 区别就是substring第二个参数不能为负数
a.substr(start,length) 第二个参数是截取长度

下面是代码的了

//如果动态加载JS文件(请写出完整的函数)
//很经典的东西
function dload(src,callback){
  var script = document.createElement('script');
  script.src = src;
  if(script.readyState){
    script.onreadystatechange = function(){
      if(script.readyStart == 'loaded' || script.readyState == 'complete'){
        callback();
      }
    }
  }
  else{
    script.onload = function(){
      callback();
    }
  }
  document.getElementsByTagName('head')[0].appendChild(script);
}
//计算出两个Date对象的相差的日数
function dayDiff(start,end){
   var a = new Date(start).getTime();
   var b = new Date(end).getTime();
   var gap = Math.floor((b-a)/(24*60*60*1000));
   return gap;
}
//判定一个字符串是否符合(2012-01-12)这样的日期格式(请写出完整的函数)
//写了个简单的 不能验证日期的正确性
function checkDate(str){
  var pa = /\d{4}\/\d{2}\/\d{2}/g;
  return pa.test(str);
}
//如何判定一个对象是数组(请写出完整的函数)
//很好的问题 还有一种解答 自己查吧~
function isArray(arr){
  return ((typeof arr == 'object') && (arr.constructor == Array));
}

//用正则取得某个标签里面的innerText
//其实就是过滤掉所有的html标签
function scriptHTML(str){
  return str.replace(/<.*?>/g,'');
}

自己写的js倒计时函数

经常搞倒计时 重复的功能让人吐 倒计时的时候也总是copy上一次搞得代码
这次小小封装一下 用起来也简单很多
用法很简单

v.count.run(’2011/10/1′,’drag’,'离国庆节还有%D天,%H小时,%M分钟,%S秒’);

第一个是结束时间(注意要写成 2010/11/11 11:11:11)这种形式,第二个是容器对应id名,在页面你要的位置添加上, 第三个是想显示的内容,里面%D这类的符号是变量, 支持上面那四个变量(天,小时,分钟,秒)
源代码如下

/**
 * @author viking
 * a simple piece of code to help you make countdowns
 */
var v = {};
v.count = (function(){
	var start = '';
	var end = '';
	var pat = '';
	var holder;
	var unix1 = 0;
	var unix2 = 0;
	var calArr;
	var palArr = ['%D','%H','%M','%S'];
	var calTime = function(unix1,unix2){
		var gap = unix2 - unix1;
		if(gap < 0){
			alert('countdown has expried,check your paras');
			return;
		}
		var dday,dhour,dmin,dsec;
		dday = Math.floor(gap/(1000*3600*24));
		dhour=Math.floor((gap%(60*60*1000*24))/(60*60*1000)*1);
		dmin=Math.floor(((gap%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
		dsec=Math.floor((((gap%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
		return{
			D:dday,
			H:dhour,
			M:dmin,
			S:dsec
		}
	}
	return {
		show:function(){
			unix1 = new Date().getTime();
			unix2 = new Date(end).getTime();
			calArr = calTime(unix1,unix2);

			for(var i=0; i< palArr.length; i++){
				var reg = new RegExp(palArr[i]);
				var sign = palArr[i].substr(1,1);
				pat = pat.replace(reg,calArr[sign]);
			}

			holder.innerHTML = pat;
		},
		run:function(end1,holder1,str1){
			end = end1;
			holder = document.getElementById(holder1);
			setInterval(function(){
				pat = str1;
				v.count.show();
			},1000)

		}
	}

})();

经典的class类 by john resig

一个非常小巧 易用的模拟class的js类 作者是大名鼎鼎的john resig 源代码也就不到100行 现在很喜欢用

用法

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  },
  dance: function(){
    return this.dancing;
  }
});

var Ninja = Person.extend({
  init: function(){
    this._super( false );
  },
  dance: function(){
    // Call the inherited version of dance()
    return this._super();
  },
  swingSword: function(){
    return true;
  }
});

var p = new Person(true);
p.dance(); // => true

var n = new Ninja();
n.dance(); // => false
n.swingSword(); // => true

// Should all be true
p instanceof Person && p instanceof Class &&
n instanceof Ninja && n instanceof Person && n instanceof Class

源代码如下 请欣赏

/* Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

文章的原始地址 请参考

http://ejohn.org/blog/simple-javascript-inheritance/

Jquery+Css3三级下拉菜单

这几天有空的时候就随便写写 想多了解一些css3的属性 本来想写一个插件的 最后不了了之 一开始想做无限极下拉 最后觉得没这个必要 没这种需求 做出来以后美化美化 用了google font。其实这玩意儿没什么难度 就是计算好css的位置 根据li下面有没有ul判断 显示或者隐藏 先做出一个好看的样子 过几天再把代码优化一下~ 现在毫无封装 乱的很

部分js代码 html结构firebug打开自己看吧

//calulate the positon
	var _holder=  $('#holder');
	var _mainlink = _holder.find('ul.dropdown>li:has(ul)');
	var _mheight = _mainlink.height();
	_mainlink.css({'position':'relative'});

	_mainlink.hover(function(){
		var that = $(this);
		var _sublist = that.find('>ul');
		that.find('a:eq(0)').addClass('active');
		_sublist.css({
			'position':'absolute',
			'top':_mheight,
			'left':'0px'
		})
		_sublist.show();
		var _sublink = _sublist.find('li:has(ul)');
		_sublink.css(
			{
				'background':'url("arrow.png") no-repeat scroll 120px center'
			}
		);
		_sublink.hover(function(){
			var that = $(this);
			var _alink = that.find('a:eq(0)');
			_alink.addClass('active');
			var _index = _sublist.find('li').index(that);
			var _swidth = that.width();
			var _multi = that.find('>ul');
			_multi.css({
				'position':'absolute',
				'left':_swidth,
				'top':'0px'
			});
			_multi.show();
		},function(){
			var that = $(this);
			that.find('a:eq(0)').removeClass('active');
			var _multi = that.find('>ul');
			_multi.hide();

		})
	},function(){
		var that = $(this);
		that.find('a:eq(0)').removeClass('active');
		var _sublist = that.find('>ul');
		_sublist.hide();
	})

查看demo 下载

经典js方法 getStyle

实际应用中, 获取元素样式在实际应用中一定常用到, 若是纯粹html中, 直接elem.style.attr就可获取,如果原来没有定义过 我们会取得一个空值 更多的时候我们是要从CSS中获取元素的最终样式属性.所以, 我们得利用IE的currentStyle和W3C的getPropertyValue获取. 下面是获取元素属性的经典方法 来在john resig

function getStyle(elem,name){
	if(elem.style[name]){
		return elem.style[name];
	}
	else if (elem.currentStyle){
		return elem.currentStyle[name];
	}
	else if(document.defaultView && document.defaultView.getComputedStyle){;
		name = name.replace(/[A-Z]/g,"-$1");
		name = name.toLowerCase();

		var s = document.defaultView.getComputedStyle(elem,"").getPropertyValue(name);
		return s;
	} else {
		return null;
	}
}