0

如何使这些函数使用 id 变量?当我这样做时,我无法setTimeout工作。

    <script type="text/javascript">
        function changeBarAWidth() {
            var bar = document.getElementById('firstbar');
            bar.style.width = lengthA + "px";
        }

        function increaseBarA() {
            if (lengthA < fullBarA) {
                changeBarAWidth();
                lengthA = (lengthA + 2);
                setTimeout("increaseBarA()", 10);  // <-- How do I pass "firstbar"?
           }
        }

        function resetLengthA() {
            lengthA = 0;
            changeBarAWidth();
        }

        var barA = 'firstbar';
        var percentA = 80;
        var fullBarA = (percentA * 2);
        var lengthA = 0;
    </script>
    <style type="text/css">
        ul {
            list-style-type: none;
        }
        .bar {
            width: 50px;
            height: 5px;
            background-color: red;
        }
        .back {
            background-color: black;
            height: 5px;
            width: 200px;
        }
    </style>
</head>
<body onload="increaseBarA()">
    <ul>
        <li class="back">
            <p class="bar" id="firstbar"></p>
        </li>
    </ul>
    <button onClick="increaseBarA()">Test Change</button>
    <button onClick="resetLengthA()">Reset</button>
4

1 回答 1

0

我不得不使用一个setTimeout(function() { YourFuncwith(params); }, 10);.

这是脚本。如果有人想要复制,请执行以下操作:

// functions to show poll reults, div width increase every tenth of a second,
// looks like poll is sliding.

// length is name of global length variable you declare, mine are at bottom of script
// I will use php to dynaimcally give variable values based on poll results.
function changeBarWidth(id, length) {
    var bar = document.getElementById(id);
    bar.style.width = length + "px";
}


/* max is how long you want the poll to slide to, my background is 200px
 * so I set to (percent*2);
 */
function increaseBar(id, max, length) {
    var full = max;

    if (length < full) {
        changeBarWidth(id, length);
        length = (length + 2);

        setTimeout(function() {
            increaseBar(id, max, length);
        }, 10);
   }
}

var barA = 'firstbar';
var percentA = 80;
var fullBarA = (percentA * 2);
var lengthA = 0;
var lengthB = 0;
ul {
    list-style-type: none;
}
.bar {
    width: 50px;
    height: 5px;
    background-color: red;
}
.back {
    background-color: black;
    height: 5px;
    width: 200px;
}
<body onload="increaseBar(barA, percentA, lengthA)">
    <div id="pollresults">
        <ul>
            <li class="back">
                <p class="bar" id="firstbar"></p>
            </li>
            <li class="back">
                <p class="bar" id="secondbar"></p>
            </li>
        </ul>
    </div>
    <button onClick="increaseBar('secondbar',fullBarA,lengthB)">Test Change</button>
</body>

于 2009-12-24T11:17:16.053 回答