大话前端

实用脚本

2018-04-11  本文已影响2人  fenerchen

一、insertAfter()

用法 insertAfter(newElement,targetElement),把newElement添加到targetElement之后

function insertAfter(newElement,targetElement){
    var parent=targetElement.parentNode;
    if(parent.lastChild==targetElement){
        parent.append(newElement);
    }else{
        parent.insetBefore(newElement,targetElement.nextSibling);
    }
}

二、addLoadEvent(func)

功能:在页面加载完毕时执行func

function addLoadEvent(func){
    var onload=window.onload;
    if(typeof window.onload!="function"){
        window.onload=func;
    }else{
        window.onload=function(){
            onload();
            func();
        }
    }
}

三、JS判断浏览器对CSS3属性是否支持的方法

1、JavaScript常用方法

var support_css3 = (function() {
    var div = document.createElement('div'),
        list = ['Ms', 'Moz', 'O', 'Webkit'],
        len = list.length;
    //用一个retrurn函数包裹很多return语句,可以避免一个函数中有很多出口的弊端。
    return function(prop) {
        // if (prop in div.style) return true;
        prop = prop.replace(/^[a-z]/, val => val.toUpperCase());
        for (let i = 0; i < len; i++) {
            if (list[i] + prop in div.style) return true;
        }
        return false;
    }
})()

使用:检测浏览器是否支持transform属性

if(support_css3('transform')){

}else{
    
}

2、JavaScript方法,不支持ie6


function isPropertySupported(prop) {
   // var div = document.createElement('div');
   //  return prop in div.style;//这样写也可以,没发现什么问题
    return prop in document.body.style;
}
//使用
alert(isPropertySupported('transform'))//true
alert(isPropertySupported('MozTransform'))

总结,不管的js的那种方法,核心就是检测属性是否在div.style对象中,只不过有的添加了浏览器前缀检测。
3、CSS.supports()方法
一般来说,不支持新属性的浏览器也不支持这个方法。哭笑。像IE浏览器(连Edge都不支持)就不支持,所以使用就会报错。因此在使用前要检测一下CSS的类型如果是function并且有supports方法就执行A,否则就实行B方案。

if(typeof CSS=='function'&&CSS.supports('display:grid')){
alert(true)
}else{
alert(false)
}

四、检测浏览器对H5属性的支持情况

function elementSupportsAttribute(element, attribute){
    var ele=document.createElement(element);
    if(attribute in ele){
        return true
    }else{
        return false
    }
}

//调用
if (elementSupportsAttribute("textarea", "placeholder") {
 
} else {
 // fallback
}
上一篇 下一篇

猜你喜欢

热点阅读