使用原型和scriptaculous隐藏和显示div元素

cli*_*ket 3 prototypejs

我正在尝试使用原型和scriptaculous来隐藏和显示div元素,但是利用原型setStyle属性的函数(下面)不起作用,我不确定问题是什么.

<script type="text/javascript" language="javascript">
    function bodyOnload() {
            $('content1').setStyle({ display: 'none' });
            $('content2').setStyle({ display: 'none' });
    }
</script>    



<script type="text/javascript" language="javascript">

    var currentId = null;

    Effect.Accordion = function (contentId) {
        var slideDown = 0.5;
        var slideUp = 0.5;

        contentId = $(contentId);

        if (currentId != contentId) {
            if (currentId == null) {
                new Effect.SlideDown(contentId, {duration: slideDown});
                } else {
                new Effect.SlideUp(currentId, {duration: slideUp});
                new Effect.SlideDown(contentId, {duration: slideDown});
            }
            currentId = contentId; 
        } else {
            new Effect.SlideUp(currentId, {duration: slideUp});
            currentId = null;
        }
    };
    </script>
Run Code Online (Sandbox Code Playgroud)

上述函数如下调用:

<div id="accordion">
    <div id="part1">
        <div id="nav1" onclick="new Effect.Accordion('content1');">
            Post a comment 1
        </div>
        <div id="content1">
            <form id="form" name="form" action="post.php" method="post">
            <textarea name="commentbody" cols="20" rows="10"></textarea>
            <button type="submit">Post Comment</button>
            <input type="hidden" name="blogID" value="1" />
            <input type="hidden" name="userID" value="3" />
            <input type="hidden" name="parentID" value="7" />
            <div class="spacer"></div></form>
        </div>
    </div>
        <div id="part2">
        <div id="nav2" onclick="new Effect.Accordion('content2');">
            Post a comment 2
        </div>
        <div id="content2">
            <form id="form" name="form" action="post.php" method="post">
            <textarea name="commentbody" cols="20" rows="10"></textarea>
            <button type="submit">Post Comment</button>
            <input type="hidden" name="blogID" value="1" />
            <input type="hidden" name="userID" value="3" />
            <input type="hidden" name="parentID" value="7" />
            <div class="spacer"></div></form>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是代码发生的事情.

  • 在ie和firefox中它什么也没做,但是当你点击调用effect.accordion方法的链接时,该方法按预期工作.问题在于原型功能不会隐藏元素.非常感谢任何帮助.

Jon*_*ski 10

maxnk已经涵盖了主要问题.

但是,Prototype建议使用dom:loaded事件而不是window.onload:

document.observe("dom:loaded", bodyOnload);
Run Code Online (Sandbox Code Playgroud)

此外,您可以尝试使用Prototype Element#toggleElement#hide代替Element#setStyle(除非每个页面上的警告适用于您的CSS).

function bodyOnload() {
    $('content1').hide();
    $('content2').hide();
}
Run Code Online (Sandbox Code Playgroud)