简体   繁体   中英

More than one onscroll elements by id

This code works, but i also want to change Class of one more Div, how can i do it? I know it doesnt work with getElementById(). Im new at JS so dont judge if this is something very simple.

<script>
window.onscroll = function() {myFunction()};

function myFunction() {
    if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
        document.getElementById("header").className = "fixed";
    } else {
        document.getElementById("header").className = "";
    }
}
</script>

i want to add class to "logo" too

<div id="header">
    <a href="index.html">
        <img id="logo">
    </a>
<ul>
    <li><a href="index.html">Etusivu</a></li>
    <li><a href="#">Kauppa</a></li>
</ul>
</div>

Well, Catfish, there's nothing stopping you from duplicating the line that already works and changing the id . I don't really understand what you mean by saying you know it doesn't work with getElementById() .

Also, if you're not using myFunction() anywhere else, it makes for cleaner code to use an anonymous function, like so:

window.onscroll = function() {
    if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
        document.getElementById("header").className = "fixed";
        document.getElementById("logo").className = "fixed";
    } else {
        document.getElementById("header").className = "";
        document.getElementById("logo").className = "";
    }
};

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