0

Is it possible to apply the javascript to multiple divs with the same id? At the moment it only applies it to the first found, I guess at [0]. Is it possible to loop through the divs and apply it that way?

<body>
        <div id="mainHolder">
            <div id="header">
                <img src="images/collapse1.png" />
            </div>
            <div id="content">
                <p>This is a collapsible panel</p>
                <img src="images/bird.jpg" height="130"/>
            </div>
        </div>
        <div id="panelBelow">
            <p>A panel is placed below the collapsible panel, just to show that when the panel above collapses the panel below is also moved up.</p>
        </div>

        <br></br>

        <div id="mainHolder">
            <div id="header">
                <img src="images/collapse1.png" />
            </div>
            <div id="content">
                <p>This is a collapsible panel</p>
                <img src="images/bird.jpg" height="130"/>
            </div>
        </div>


    </body>
    <script type="text/javascript">
        var header = null;
        var content = null;
        var mainHolder = null;
        var expandCollapseBtn = null;
        var heightValue = 0;

        header = document.getElementById("header");
        content = document.getElementById("content");
        mainHolder = document.getElementById("mainHolder");
        expandCollapseBtn = header.getElementsByTagName('img')[0];

        heightValue = mainHolder.offsetHeight;

        header.addEventListener('click', handleClick, false);
        mainHolder.addEventListener('webkitTransitionEnd',transitionEndHandler,false);

        function handleClick()
        {
            if(expandCollapseBtn.src.search('collapse') !=-1)
            {
                mainHolder.style.height = "30px";
                content.style.display = "none";
            }
            else
            {
                mainHolder.style.height = heightValue + "px";
            }
        }

        function transitionEndHandler()
        {
            if(expandCollapseBtn.src.search('collapse') !=-1)
            {
                expandCollapseBtn.src = "images/expand1.png";
            }
            else{
                expandCollapseBtn.src = "images/collapse1.png";
                content.style.display = "block";
            }
        }

        </script>
4

2 回答 2

0

像这样改变你的mainHolder元素:

<div class="mainHolder">...</div>

然后addEventListeners 到每个元素,如下所示:

var mainHolderElements = getElementsByClassName('mainHolder');

for (var i = 0, length = mainHolderElements.length; i < length; i++) {
    mainHolderElements[i].addEventListener(...);
}
于 2013-10-04T00:33:15.163 回答
0

只能有一个具有 id 的元素。

将您的 id 更改为一个类并通过该类选择元素。正如这个答案: https ://stackoverflow.com/a/3887663/498699

于 2013-10-04T00:27:06.613 回答