简体   繁体   中英

Webkit Javascript Causes Page Jumping

Using this code

v=new Date();
var bxx=document.getElementById('bxx');
function t(){
    n=new Date();
    ss={time};
    s=ss-Math.round((n.getTime()-v.getTime())/1000.);
    m=0;h=0;
    if(s<0){
        bxx.innerHTML='<a ';
    }else{
        if(s>59){m=Math.floor(s/60);s=s-m*60;}
        if(m>59){h=Math.floor(m/60);m=m-h*60;}
        if(s<10){s="0"+s}
        if(m<10){m="0"+m}
        bxx.innerHTML=h+':'+m+':'+s+'<br>{name}</a>';
    }
    window.setTimeout("t();",999);
}
t();

Whenever t() is called, the page jumps to the top of the screen. Any ideas?

The {} are server parsed variables, but they should be causing any problem.

By jumping, I mean that the page, scrolled to the bottom, suddenly jumps to the top of the page

I don't know about the jumping, but that code has a couple of issues:

1) Hopefully all of these variables are declared somewhere that you haven't shown? (If not, you're falling prey to the Horror of Implicit Globals , which I'd recommend avoiding.)

2) This code:

bxx.innerHTML='<a ';

...is asking the browser to parse an invalid HTML fragment.

3) As is this code:

bxx.innerHTML=h+':'+m+':'+s+'<br>{name}</a>';

...as h and such are numbers, and so you end up with 1:23:45<br>name</a> .

The innerHTML property cannot contain partial element tags, because it represents the entire content of an element, and elements can't cross over one another like that (the DOM is a tree, not a weave).

You'll want to modify the code so that it's always writing a fully-formed a tag to the bxx.innerHTML property, all in one go.

Once you do that, it could still cause some minor jumping, if the former content of the element has different dimensions than the new content. You can mitigate that with CSS (an inline-block element with width and height, etc.).

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