JS和CSS的多浏览器兼容(2)

时间:2021-01-04 19:15:35

2.Css的浏览器兼容性

方法一,根据不同的浏览器加载不同的css file

<!DOCTYPE html> 

<html>

<head>

<title>Test Page</title>

<link href="ie.css" rel="stylesheet" type="text/css" />

</head>

<script type="text/javascript">

function loadjscssfile(filename, filetype) {

if (filetype == "js") { //if filename is a   external JavaScript file

var fileref = document.createElement('script')

fileref.setAttribute("type", "text/javascript")

fileref.setAttribute("src", filename)

}

else if (filetype == "css") { //if filename is an   external CSS file

var fileref = document.createElement("link")

fileref.setAttribute("rel", "stylesheet")

fileref.setAttribute("type", "text/css")

fileref.setAttribute("href", filename)

}

if (typeof fileref != "undefined")

document.getElementsByTagName("head")[0].appendChild(fileref)

}

if   (navigator.appName == "Netscape") {

loadjscssfile("chrome.css", "css");

}

</script>

<body>

<div class="container">

</div>

</body>

</html>

Chrome专用的css file中只需要写和ie不同的部分即可,不需要全部copy, 后加载的样式会自动覆盖原有的样式。

 

 

方法二,Css Hack

<!DOCTYPE html>

<html>

<head>

<title>Css Hack</title>

<style>

#test

{

width:300px;

height:300px;

background-color:blue;

}

@media screen and (-webkit-min-device-pixel-ratio:0){ #test {background-color:gray;} }  /*chrome and   safari浏览器认识*/

</style>

</head>

<body>

<div id="test">test</div>

</body>

</html>

@media screen and (-webkit-min-device-pixel-ratio:0){ #test {background-color:gray;} }这个是浏览器chrome和safari的。即将样式用

@media screen and (-webkit-min-device-pixel-ratio:0){}装起来