javascript JS/jQuery 在滚动事件上交换图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19406435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:29:02  来源:igfitidea点击:

JS/jQuery swap image on scroll event

javascriptjqueryhtmlcss

提问by bradmagnus

I've got a site menu that works pretty much like this: http://jsfiddle.net/sinky/XYGRW/(found that here on stackoverflow)

我有一个网站菜单,它的工作原理非常像这样:http: //jsfiddle.net/sinky/XYGRW/(在 stackoverflow 上找到)

My question is that the designer wants the logo in the nav (home button), to be switch to a smaller icon. Not just scale down, but actually change image. Can I use the scroll event I'm already using for the other addClass commands to change the img src?

我的问题是设计师希望导航(主页按钮)中的徽标切换到较小的图标。不仅缩小,而且实际上改变形象。我可以使用我已经用于其他 addClass 命令的滚动事件来更改 img src 吗?

$(window).scroll(function () {
    if ($(document).scrollTop() == 0) {
        $('#header').removeClass('tiny');
        $('#menu-spacing').addClass('nav-margin-top');
    } else {
        $('#header').addClass('tiny');
        $('#menu-spacing').removeClass('nav-margin-top')
    }
}); 


HTML
<div id="header" class="header fixed">    
    <div class="contain-to-grid">
            <nav class="row top-bar">
                <ul class="title-area">
                    <li><img src="img/resolute_logo.png" width="195" height="103" alt=""/>    </li>
    <li class="toggle-topbar menu-icon"><a href="#"><span></span></a></li>
                </ul>
                <div id="menu-spacing" class="hide-for-medium-down nav-margin-top">

回答by Mister Epic

Sure:

当然:

$(window).scroll(function () {
    if ($(document).scrollTop() == 0) {
        $('#header').removeClass('tiny');
        $('#menu-spacing').addClass('nav-margin-top');
        $('.title-area img').attr('src', 'img/resolute_logo.png');
    } else {
        $('#header').addClass('tiny');
        $('#menu-spacing').removeClass('nav-margin-top');
        $('.title-area img').attr('src', 'your-new-image.png');
    }
}); 

ref: http://api.jquery.com/attr/

参考:http: //api.jquery.com/attr/

回答by Paraíso

Why not just add the images to your css?

为什么不直接将图像添加到您的 css 中?

.header.tiny {
    height:40px;
    background: url(...);
}

The rest of the code you already have

您已经拥有的其余代码

On jsfiddle

jsfiddle 上