导读:
基本是按照张鑫旭大佬的方法,依葫芦画瓢。
一.w3c浏览器实现方法(ie9以上不支持)
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: grayscale(100%);
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
二.ie浏览器实现方法
<script>
if(window.ActiveXObject || "ActiveXObject" in window){
console.log("我是ie浏览器")
var scriptNode = document.createElement("script");
scriptNode.type = 'text/javascript'
scriptNode.src = 'http://james.padolsey.com/demos/grayscale/grayscale.js'
document.body.appendChild(scriptNode);
scriptNode.onload=scriptNode.onreadystatechange=function(){
if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){
grayscale(document.getElementsByTagName('body'));
console.log('done');
}
}
}
</script>
三.整体代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body{
/* filter: grayscale(100%) blur(1px); */
/* blur 模糊程度 */
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: grayscale(100%);
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
}
.container{
width: 100px;
height: 100px;
background-color: red;
}
.container2{
width: 100px;
height: 100px;
}
.container2 img{
width: 100%;
height: 100%;
}
</style>
<body>
<div class="container"></div>
<div class="container2">
<img src="./851207.jpg">
<!-- 随便插一张图片好了 -->
</div>
</body>
<script>
if(window.ActiveXObject || "ActiveXObject" in window){
console.log("我是ie浏览器")
var scriptNode = document.createElement("script");
scriptNode.type = 'text/javascript'
scriptNode.src = 'http://james.padolsey.com/demos/grayscale/grayscale.js'
document.body.appendChild(scriptNode);
scriptNode.onload=scriptNode.onreadystatechange=function(){
if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){
grayscale(document.getElementsByTagName('body'));
console.log('done');
}
}
}
</script>
</html>
四.相关知识参考
1.各大浏览器对filter的支持
2.来自张鑫旭大佬的使用CSS将图片转换成黑白的方案
3.JS判断各种浏览器,根据判断动态引入不同的CSS文件、JS文件
4.判断引入的js文件是否加载完毕
网友评论