相信很多同学在使用IE的opacity上都会觉得很不爽,因为IE对透明元素的支持很“独树一帜”,当然了,IE的兼容性问题由来已久,不光这个元素,那么,很多人在使用juery的fadeIn函数做淡入效果的时候会遇到问题,例如下面的例子,以下是例子的源文件,html、js、css文件各一个:
1219.html
[html]<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="1219.js"></script>
<link rel="stylesheet" href="1219.css" type="text/css" />
</head>
<body>
<div class="button"></div>
<div class="display"></div>
</body>
</html>[/html]
1219.js
[js]$(document).ready(function(){
$(‘.button’).click(function(){
$(‘.display’).fadeIn();
});
});[/js]
1219.css
[css].button{width: 100px;height: 20px;border: 1px solid red; }
.display{display: block;width: 100px;height: 100px; border: 2px aqua dotted; display: none;filter:alpha(opacity=35);-moz-opacity:0.35;-kHTML-opacity: 0.35;opacity: 0.35;background: #000;}[/css]
这个例子的作用是当我点击class=button的div的时候,会弹出一个class=display的div,当然这个弹出层的效果是淡入的,而且背景色为黑色,透明度为35%,其实这个效果我们经常做,比如登陆时的遮罩层,当然我们今天是为了讲兼容性方案,就略过遮罩层。
这个页面在ie9以及火狐和chrome等浏览器下面正常,但是在ie8以下就会出问题,透明效果不见了。这其实是ie的一个bug,是由于filter导致的,因此我们需要自己来处理一下filter这个元素,okay,我们来重写一下jquery的fade:
[html]<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery.js"></script>
<!– 重写jquery的fade方法 –>
<script type="text/javascript">
jQuery.fn.fadeIn = function(speed, callback) {
return this.animate({
opacity: ‘show’
}, speed, function() {
if (jQuery.browser.msie)
this.style.removeAttribute(‘filter’);
if (jQuery.isFunction(callback))
callback();
});
};
jQuery.fn.fadeOut = function(speed, callback) {
return this.animate({
opacity: ‘hide’
}, speed, function() {
if (jQuery.browser.msie)
this.style.removeAttribute(‘filter’);
if (jQuery.isFunction(callback))
callback();
});
};
jQuery.fn.fadeTo = function(speed,to,callback) {
return this.animate({
opacity: to
}, speed, function() {
if (to == 1 && jQuery.browser.msie)
this.style.removeAttribute(‘filter’);
if (jQuery.isFunction(callback))
callback();
});
};
</script>
<script type="text/javascript" src="1219.js"></script>
<link rel="stylesheet" href="1219.css" type="text/css" />
</head>
<body>
<div class="button"></div>
<div class="display"></div>
</body>
</html>[/html]
你会发现多了一段js,是的,那就是我们要重写fade方法的代码,将这段代码放在引入jquery类库之后,那么现在在ie8下,我们使用fadeIn就会正常啦。
这时候很多同学会说了,哇,好麻烦哦,有没有更好的方法呢,呵呵,还真有一个,那就是jquery的fadeTo,这个方法是以渐变的方式调整到某一个透明度,在IE下,这个小方法这个方法正常使用,那我么你可以修改js文件:
1219.js
[js]$(document).ready(function(){
$(‘.button’).click(function(){
// $(‘.display’).fadeIn();
$(‘.display’).fadeTo(‘slow’,0.5);
});
});[/js]
用了这个方法之后,就不会要重写jquery的fade方法了。
2023年六月 一 二 三 四 五 六 日 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 -
近期文章