Javascript淡入淡出不起作用

时间:2011-09-07 11:24:46

标签: javascript jquery html css

我正在使用一些javascript来淡化页面顶部的几个消息栏 - 有点像stackoverflow那样:)

我有:

<div id='message' style="display: none;">
    <span>Wow, that was quick! - below is a preview of your page.</span>
    <a href="#" class="close-notify">X</a>
</div>
<div id='message' style="display: none;">
    <span>Try posting something interesting</span>
    <a href="#" class="close-notify">X</a>
</div>

CSS:

#message {height:30px;width:100%;z-index:105;text-align:center;color:white;padding:10px 0px 10px 0px;background-color:#8E1609;}
#message span {text-align: center;width: 95%;float:left;}
.close-notify {white-space: nowrap;float:right;margin-right:10px;color:#fff;text-decoration:none;border:2px #fff solid;padding-left:3px;padding-right:3px}
.close-notify a {color: #fff;}

和Javascript:

$(document).ready(function() {
    $("#message").fadeIn("slow");
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
        return false;
    });
});

但遗憾的是只显示了第一条消息。怎么会?当然第二个也应该显示出来?

感谢

9 个答案:

答案 0 :(得分:2)

ID只能在页面上使用一次。它是一个唯一的标识符。

如果您有多个项目,则需要使用课程。

<强> HTML

<div class="message">Some Message</div>
<div class="message">Some Other Message</div>

<强>的jQuery

$('.message').fadeIn('slow');

以下是演示:http://jsfiddle.net/GBjxH/

答案 1 :(得分:2)

id属性在页面中的所有元素中应该是唯一的。更改HTML,CSS和JavaScript以使用class="message"代替id="message",它会正常工作。

从技术上讲,这里发生的是jQuery看到#message选择器并尝试使用document.getElementById(这是最快的)找到元素。此函数仅返回一个元素,在本例中是第一个元素。所以第二个永远不会有机会被处理。

您还有一个错误:由于代码现在处于停止状态,点击“关闭”链接会使所有消息消失。您需要稍微调整click处理程序以使其按预期运行。

<强> See all of this in action here

答案 2 :(得分:0)

你的两个元素都有相同的ID #message - 一个ID应该是唯一的,所以这应该是一个类。

答案 3 :(得分:0)

您不能将ID用于两个元素,请尝试使用类!

<div class='message' style="display: none;">

$('.message').fadeIn();

答案 4 :(得分:0)

这是因为他们都有相同的身份证明。 fadeIn仅用于第一个。如果你想为它们(或全部)做这些,那就应用一个类并做一些像

这样的事情

$(".classname").each(...

答案 5 :(得分:0)

您不能拥有两个相同的ID

答案 6 :(得分:0)

您不应该使用相同'id'的元素。

答案 7 :(得分:0)

ID是独一无二的!您不能拥有2个具有相同ID的元素。使用类

答案 8 :(得分:0)

您不应该有多个具有相同ID的项目,而是使用类。