繁体   English   中英

固定在滚动位置上的图像

[英]Fixed Image On Scroll Shifting Position

JSFiddle: https ://jsfiddle.net/DTcHh/19451/

我正在使用Bootstrap 3构建网站。在滚动中,我有一个图像,通过将位置更改为固定可粘贴到页面上。 此方法有效,但是一旦固定,它总是会移位。 我知道这与页边距有关(而且我玩过像素,这似乎可以解决问题,对于响应型网站,页边距左必须为%)。 这是代码:

的HTML

<div class="row">
            <div class="col-sm-5">
                <h2 class="white">Some Text</h2>
            </div>
            <div class="col-sm-7">
                <img class="img-responsive screen-phone" src="img/phone.png">
            </div>
</div><!--END ROW-->

的CSS

.screen-phone{
    max-width:300px;
    margin-top:25px;
    margin-left:25%;
    z-index:999;

}

Java脚本

$(document).ready(function(){

$(window).scroll(function () {
    if ($(this).scrollTop()>1120){
        $('.screen-phone').css('position','fixed').css('top','0');
    }else{$('.screen-phone').css('position','static');
    };
 });
});

尝试这个

的CSS

/* Latest compiled and minified CSS included as External Resource*/

/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

.screen-phone{
    max-width:300px;
    margin-top:25px;
    //margin-left:25%;
    z-index:999;
 float:right;
}

的JavaScript

/* Latest compiled and minified JavaScript included as External Resource */

$(document).ready(function(){

    // var stickyPhone = ($#)

    $(window).scroll(function () {
        if ($(this).scrollTop()>500){
            $('.screen-phone').css('position','fixed').css('right','0');
        }else{$('.screen-phone').css('position','relative');
        };
    });
});

我删除了左边距,并添加了一个浮动右边。 然后在JS上,我将位置更改为left:0。 它可以正常工作。

我进行了一些更改,使其生效:

  1. 将类名称移动到div元素而不是img元素
  2. 仅在必要时使用布尔变量对CSS进行更改
  3. 500像素测试对于文本大小来说太长了。 调用时,由于图像固定而导致的尺寸更改将缩小到500以下,从而强制进行其他更改,依此类推。

请参阅更新的jsfiddle: https ://jsfiddle.net/DTcHh/19475/

好吧,我知道了。 需要做的是在包含的DIV上放置一个单独的类。 您留下它:(无论您的百分比值在这里)。 您将左边距关闭包含的图像。 如果像我一样使用Bootstrap,则必须解决边距问题,您可以像创建删除行和col-sm-7边距那样创建两个类。 就我而言:

.screen-phone{
 max-width:300px;
 margin-top:25px;
 /*Removed margin-left:25%*/
 z-index:999;

}

.sticker{
 left:25%
}

.zero-row{
 margin:0;
}

.no-margin{
 width:0;
}

HTML:

<div class="row zero-row">
        <div class="col-sm-5">
            <h2 class="white">Some Text</h2>
        </div>
        <div class="col-sm-7 no-margin sticker">
            <img class="img-responsive screen-phone" src="img/phone.png">
        </div>
</div><!--END ROW-->

更新的Fidde: https ://jsfiddle.net/1chkghhq/1/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM