[英]Where and what i am doing wrong in my JS Code
I am stuck why this code is not working. 我很困惑为什么此代码无法正常工作。 Why Image position not fixed when i scroll down the window.
为什么当我向下滚动窗口时图像位置不固定。
I know this is a very common question help would be appreciated. 我知道这是一个非常常见的问题,我们将不胜感激。
$(window).scroll(function () { if($(window).scrollTop() === 200){ $("#dataImg").css({'position':'fixed','top':'0px'}); } });
.container { height: 1500px; background: #000; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <img src="http://www.placehold.it/200x300" id="dataImg"> </div>
I think the problem is with the "$(window).scrollTop === 200". 我认为问题出在“ $(window).scrollTop === 200”。 You want to use > or < depending on your situation like this:
您要根据实际情况使用>或<这样:
$(window).scroll(function () {
if($(window).scrollTop() > 200){
$("#dataImg").css({'position':'fixed','top':'0px'});
}
});
I suppose you want to fix that image when you scroll down over 200px. 我想您想在向下滚动200px时修复该图像。 You can change your Javascript code to following:
您可以将Javascript代码更改为以下内容:
$(window).scroll(function () {
if($(window).scrollTop() >= 200){
$("#dataImg").css({'position':'fixed','top':'0px'});
} else {
$("#dataImg").css({'position': '', 'top' : ''});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.