【发布时间】:2014-04-01 18:45:41
【问题描述】:
我发现 JQuery 真的很慢,所以我决定创建自己的 fadeIn 和 fadeOut 函数,这样我就可以像 jquery 一样轻松地调用它们。我已经完成了一半,因为它完全可以正常工作,但不幸的是,当我单击 fadeIn 时,它会不断地重新淡入,而当我单击 fadeOut 时,它会不断地淡出。
我尝试使用显示:无;和 display: javascript 中的块样式,但仅适用于淡出。它现在完全可以在 IE6 + 7 上运行!!。问题出在css内部。如果有人现在可以帮助使用 javascript,我将非常感激。
这是我的代码:
HTML:
<html>
<body>
<a id="fadeI">FadeIn</a>
<a id="fadeO">FadeOut</a>
<div id="message"></div>
</body>
</html>
CSS:
<style>
#fadeI, #fadeO{
cursor: pointer;
margin-left: 10px;
zoom: 1;
}
#message{
background: url('pictures/iphone1.png') no-repeat;
width:90px;
height: 158px;
z-index: 1;}
</style>
Javascript:
<script>
window.onload = function() {
function fadeOut(id, seconds) {
var opacity = 1;
var interval = seconds * 10;
var outListener = null;
outListener = setInterval(function() {
opacity = fadeOutInterval(opacity, id, outListener);
} , interval);
}
function fadeOutInterval(opacity, id, outListener) {
opacity = opacity - 0.1;
setOpacity(id, opacity);
if(opacity < 0) {
clearInterval(outListener);
//document.getElementById(id).style.display = 'none';
}
return opacity;
}
function fadeIn(id, seconds) {
var opacity = 0;
var interval = seconds * 10;
var InListener = null;
InListener = setInterval(function() {
opacity = fadeInInterval(opacity, id, InListener);
} , interval);
}
function fadeInInterval(opacity, id, InListener) {
opacity = opacity + 0.1;
setOpacity(id, opacity);
if(opacity > 1) {
clearInterval(InListener);
}
return opacity;
}
function setOpacity(id, level) {
document.getElementById(id).style.opacity = level;
document.getElementById(id).style.MozOpacity = level;
document.getElementById(id).style.KhtmlOpacity = level;
document.getElementById(id).style.filter = "alpha(opacity="
+ (level * 100) + ");";
}
//delay fadeOut
setTimeout(delay, 3000);
function delay(){
fadeOut('message', 1)
clearTimeout(delay,1);
return false;
}
//Call functions
var fadeI = document.getElementById('fadeI');
var fadO = document.getElementById('fadeO');
fadeI.onclick = function() {
fadeIn('message', 1);
};
fadeO.onclick = function() {
fadeOut('message', 1);
};
};
</script>
【问题讨论】:
-
您不必在window.onload中定义函数,您可以在外部进行,以便全局访问它们
-
我试过了,但是没用..
-
我猜你在
setOpacity中遇到了错误,而且你的时间间隔永远不会被清除。 -
我没有看到任何错误...还有其他建议/答案吗?
-
我知道这不会解决您的 JS 问题,但我强烈建议您在 CSS 中进行不透明度转换。如果不出意外,您将获得更好的性能。
标签: javascript jquery html fadein fadeout