Javascript& html:不透明度更改导致意外行为

时间:2011-05-03 02:30:21

标签: javascript html dom

我打算通过使用绝对定位和通过Javascript改变它们的不透明度,在3个元素之间进行简单的淡入淡出过渡,但是下面的代码不能像我预期的那样工作,我不确定为什么。

<html>
<head>
<style>
#item0, #item1, #item2 {
    opacity: 0.0;
    position: absolute;
    top: 100px;
    left: 100px;
    border: 1px solid #000;
    height: 200px;
    width: 200px;
    line-height: 200px;
    text-align: center;
    vertical-align: middle;
    font-size: 26px;
}
#item0 { opacity: 1.0; }
</style>
<script>
var count = 0;
var items;
function init(){
    items = document.getElementById("container").getElementsByTagName("div");
    setInterval(fade, 5000);
}
function fade(){
    fadeElements(items[count], items[(count + 1) % 3]);
    count = (count + 1) % 3;
}
function fadeElements(prevItem, nextItem){
    prevItem.style.opacity -= 0.1;
    nextItem.style.opacity += 0.1;
    if(nextItem.style.opacity < 1.0){
        setTimeout(function(){fadeElements(prevItem, nextItem)}, 50);
    } else {
        nextItem.style.opacity = 1.0;
        prevItem.style.opacity = 0.0;
    }
}
</script>
</head>
<body onload="init();">
    <div id="container">
    <div id="item0"> 0 </div>
    <div id="item1"> 1 </div>
    <div id="item2"> 2 </div>
</div>
</body>
</html>

我认为这与使用+ = with element.style.opacity有关,但Firefox给了我无用的错误,Chrome根本没有错误。

2 个答案:

答案 0 :(得分:5)

element.style对象的成员是字符串。所以试试这个

prevItem.style.opacity = parseFloat(prevItem.style.opacity) - 0.1;
nextItem.style.opacity = parseFloat(nextItem.style.opacity) + 0.1;

答案 1 :(得分:2)

正在检索

element.style.opacity作为字符串。要解决此问题,请替换以下行:

prevItem.style.opacity -= 0.1;
nextItem.style.opacity += 0.1;

有了这些:

prevItem.style.opacity = (+prevItem.style.opacity) - 0.1;
nextItem.style.opacity = (+nextItem.style.opacity) + 0.1;

此外,对于第一次迭代,零点将暂时闪烁。这是因为虽然它在CSS中设置为1.0,但它在HTML中没有style属性。您可以通过在1.0init行后面)中将其不透明度设置为items =来解决此问题:

items[0].style.opacity = 1.0;
相关问题