简体   繁体   中英

Scroll Effect doesn't work on chrome

I have a scroll effect that changes the colour of the background by finding the users position on the page and using that to set the colour. This works fine on safari and in Atom Html Previewer however when I checked it on chrome it didn't work. My website is harry-day.con

Any suggestions on why it doesn't work or how to fix it? I tried modifying the JS slightly but nothing worked.

Here is the JavaScript I am using:

function scroll(){
    var body = document.body,
    html = document.documentElement;
    var height = html.scrollHeight - html.clientHeight;
    var color = Math.round((body.scrollTop / height) * 255);
    body.style.backgroundColor = "rgb("+color+","+color+","+color+")";
}

Edit: I tried using var color = Math.round((html.scrollTop / height) * 255); however now it does not work when I tested it locally in Safari.

You can check this for a cross-browser way of getting current scroll position:

var doc = document.documentElement;
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

 function scroll(){ var body = document.body; var doc = document.documentElement; var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); var height = doc.scrollHeight - doc.clientHeight; var color = Math.round((top / height) * 255); body.style.backgroundColor = "rgb("+color+","+color+","+color+")"; } window.addEventListener('scroll', scroll); 
 body { height: 1400px; } 

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