ie下使用jquery的fadeIn,opacity透明效果无效的解决方案

相信很多同学在使用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方法了。

Avatar photo

About Blackford

这是个最好的时代,这是个最坏的时代,这是个充满希望的春天,这是个令人绝望的冬天,我们前面什么都有,我们前面什么都没有。梦想,让我们一次次的走远,又一次次的回头,一个关于人生的梦想还在不断奔跑,带着喜悦和疼痛,不过一切才刚刚开始,并且直到今天也远远没有结束
This entry was posted in 前端设计 and tagged , , . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用*标注