图像将随页面一起滚动

Image becomes scrollabe with the page

本文关键字:一起 滚动 图像      更新时间:2023-09-26

我有这样的代码,用于从第三方系统提供图像:

var bbimagebannerfile = "";
document.write("<a href='"%%__REDIRECT%%'" target='"_blank'"><img src='"" + bbimagebannerfile + "'" border='"0'" /></a>");

此图像位于页面底部。我想做的是,一旦用户到达页面的位置,就让这个图像与页面一起滚动,当用户向上滚动时,这个图像就会再次变为静态。有人能帮我吗?

仅举一个例子:

<div id="fixed-image"></div> 

如果我们假设上面的HTML是您正在提供的内容。你可以添加这个css:

#fixed-image {
    width: 100%;
    height: 100px;
    background-color: red;
    position: fixed;
    bottom: 0;
}

在您的情况下,可以尝试添加具有上述样式的类属性。

JS Fiddle:http://jsfiddle.net/df6tmLrg/

另一个使用javascript的演示:http://codepen.io/FakeHeal/pen/qEgxKN(codepen,因为jsfiddle不允许document.write

var bbimagebannerfile = "https://avatars2.githubusercontent.com/u/1038697?v=3&s=460";
document.write("<a href='"%%__REDIRECT%%'" target='"_blank'" class='"bottom-fixed'"><img src='"" + bbimagebannerfile + "'" border='"0'" width="100" /></a>");

和css:

.bottom-fixed {
    width: 100%;
    height: 100px;
    position: fixed;
    bottom: 0;
}

更新:如果使用jQuery,则可以使用.scroll():

var t =  $("#fixed-image").offset().top; 
$(document).scroll(function(){
    if($(this).scrollTop() > t)
    {   
        $("#fixed-image")
        .css('position', 'fixed') //we change the position to fixed
        .css('top',0); // and the top to zero
    } else {
        $("#fixed-image")
        .css('position', 'static') //we change the position to fixed
        .css('top',0); // and the top to zero
    }
});

下面是一个演示:http://jsfiddle.net/df6tmLrg/2/