示例1:
关于事件对象
MSIE:window.event, cancelBubble, returnValue, srcElement, button(鼠标按键,1,4,2,左中右)
W3C:event, stopPropagation(), preventDefault(), target, button(鼠标按键,0,1,2,左中右)
示例2:
得到页面中某点坐标
示例代码:
function getPointInPage(eventObject) {
eventObject = eventObject || getEventObject(eventObject);
var w3cDom = document.documentElement;
return {
'x': eventObject.pageX || (eventObject.clientX + w3cDom.scrollLeft) || document.body.scrollLeft,
'y': eventObject.pageY || (eventObject.clientY + w3cDom.scrollTop) || doucument.body.scrollTop
};
}
示例3:
将连字符型字符串变为驼峰型字符串
示例代码:
function camelize(str) {
return str.replace(/-(w)/g, function (allMathches, part1) {
return part1.toUpperCase();
});
}
alert(camelize('s-a-ad-ee'));
=> sAAdEe
示例4:
将驼峰型字符串变为连字符型字符串
示例代码:
function unCamelize(str) {
return str.replace(/([A-Z])/g, function (allMathes, part1) {
return '-' + part1.toLowerCase();
});
}
示例5:
得到节点类名
示例代码:
String.prototype.trim = function () {
return this.replace(/^s+|s+$/g, '');
};
function getClassName(element){
return element.className.replace(/s+/g, ' ').trim().split(' ');
}
var arr = getClassName(document.getElementById('ceshi'));
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
示例6:
判定某节点是否含有某类名
示例代码:
function hasClassName (element, className) {
if (!(element = $(element))) {
return false;
}
var classArr = getClassName(element);
for (var i = 0; i < classArr.length; i++) {
if (classArr[i] === className) {
return true;
}
}
return false;
}
示例7:
关于值传递,共享对象
示例代码:
var arr = [3, 5, 55, 25];
var len = arr.length;
alert(arr.length);
arr.splice(1, 1);
alert(arr.length);
alert(len);
=> 4
=> 3
=> 4
示例8:
增加类名
示例代码:
function addClassName(element, className) {
if (!(element = $(element))) {
return false;
}
if (element.className) {
element.className += (element.className ? ' ' : '') + className;
}
return true;
}
示例9:
删除类名
示例代码:
function removeClassName(element, className) {
if (!(element = $(element))) {
return false;
}
var classArr = getClassName(element);
var len = classArr.length;
for (var i = (len - 1), i >= 0; i--) {
if (classArr[i] === className) {
arr.splice(i, 1);
}
}
return (len === arr.length) ? false : true;
}
示例10
设置节点样式
示例代码:
function setStyle(element, styles) {
if (!(element = $(element))) {
return false;
}
for (property in styles) {
if (styles.hasOwnProperty(property)) {
if (element.style.setProperty) {
element.style.setProperty(unCamelize(property), styles[property], null); //第三个参数,设置优先级
} else {
element.style[camelize(property)] = styles[property];
}
}
}
}
示例11
获得节点某样式
示例代码:
function getStyle(element, property) {
if (!(element = $(element))) {
return false;
}
var value = element.style[camelize(poperty)];
if (!value) {
if (document.defaultView && document.defaultView.getComputedStyle) {
var css = document.defaultView.getComputedStyle(element, null); //第二个参数代表伪类
value = (css ? css.getPropertyValue(property) :null);
} else if (element.currentStyle) {
value = element.currentStyle[camelize(property)];
}
}
return value === 'auto' ? '' : value;
}