简体   繁体   中英

javascript setInterval() working in Dreamweaver but not in Chrome

I'm trying to make an image drop up/down from a menu whenever the user clicks on the menu image which has onClick="move()" in the tag. So far The image starts at the top of the page, behind the menu, so it is hidden, then slides down as intended. However, after the image reaches it's stopping point, clicking the menu again does nothing at all when I test the page in both IE and Chrome. In Dreamweaver, the code executes as intended, with the ability to slide the image up after it reaches the bottom and back down again. I've tried changing the call to setInterval() because I assumed that is where the problem was but nothing seems to be working. Why does Dreamweaver execute the code properly but not Chrome or IE?

    var onMusic=false;
    var id;
    function move() {
        if(!onMusic) {
          moveDown()        
        }
        else {
            moveUp()
        }
    }


    function moveUp() {
        top=100
        id = setInterval(function() {
            top-=10  // update parameters 
            document.getElementById('guitar').style.top = top + 'px' // show frame
            if (top <= -500)  {// check finish condition
                onMusic=false
                clearInterval(id)
            }
         }, 10) // draw every 10ms
    }

    function moveDown() {
        var top=-500
        id = setInterval(function() {
            top+=10  // update parameters 
            document.getElementById('guitar').style.top = top + 'px' // show frame
            if (top == 100)  {// check finish condition
                onMusic=true
                clearInterval(id)
            }
        }, 10) // draw every 10ms
    }

id is only visible from the scope of the moveDown function. Make it global so that you can call clearInterval(id) in moveUp .

Change

function moveDown() {
    var top=-500
    var id = setInterval(function() {

to

var id;
function moveDown() {
    var top=-500
    id = setInterval(function() {

And changing the dom every tenth of millisecond ( .1 ) might be a little extrem...

I think the problem was:

top=100
// should be
var top = 100;

You can try in the console to see what I mean:

>top = 12 
12 
> top 
Window {top: Window, window: Window, location: Location, Proxy: Object, external: Object…}

But I cleaned it up a little more in jsfiddle: http://jsfiddle.net/pNh57/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM