基本上我正在使用侧边栏,只有在浏览器窗口到达时才会滚动。
更新2:
这是我目前正在使用的代码:
$(function() {
var $sidebar = $("#sidebar"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 15;
$window.scroll(function() {
if ($window.scrollTop() > offset.top) {
$sidebar.addClass('fixed');
} else {
$sidebar.removeClass('fixed');
}
});
});
我不再收到错误,但滑动不起作用。这里的小提示显示了所需的效果,我的CSS完全相同:http://jsfiddle.net/dKDJz/647/
答案 0 :(得分:2)
如果此代码适用于您的小提琴,您可能希望检查2件事:
可能是您的代码在元素存在/呈现之前运行。在这种情况下,使用ready函数
包装您的代码$(function() {
// your code
});
如果您未加载jQuery库文件,请在页面中的标记内添加。
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
答案 1 :(得分:1)
您需要将选择器放在doc ready包装器中。 当您尝试运行选择器时,基本上#sidebar不可用。
$(document).ready(function(){
var $sidebar = $("#sidebar"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 15;
$window.scroll(function() {
if ($window.scrollTop() > offset.top) {
$sidebar.addClass('fixed');
} else {
$sidebar.removeClass('fixed');
}
});
});
答案 2 :(得分:1)
var topPadding = 15;
$(window).scroll(function() {
//alert($(window).scrollTop())
if ($(window).scrollTop() > $("#sidebar").offset().top) {
$("#sidebar").addClass('fixed');
} else {
$("#sidebar").removeClass('fixed');
}
});