我需要一段代码在我的网站中使用(我几乎找不到),但是当我在html文件中使用它时,它将无法正常工作。
我试图将它放在<html>
前面,无论头部还是 body 都无效。
也尝试过$(document).ready(function() { ... });
我正在使用:
<script src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script>
但也许我需要另一个
这是jsfiddle:http://jsfiddle.net/Tgm6Y/1447/。
var windw = this;
$.fn.followTo = function ( elem ) {
var $this = this,
$window = $(windw),
$bumper = $(elem),
bumperPos = $bumper.offset().top,
thisHeight = $this.outerHeight(),
setPosition = function(){
if ($window.scrollTop() > (bumperPos - thisHeight)) {
$this.css({
position: 'absolute',
top: (bumperPos - thisHeight)
});
} else {
$this.css({
position: 'fixed',
top: 0
});
}
};
$window.resize(function()
{
bumperPos = pos.offset().top;
thisHeight = $this.outerHeight();
setPosition();
});
$window.scroll(setPosition);
setPosition();
};
$('#one').followTo('#two');
最佳答案
在文档准备功能中可以正常工作。您的JavaScript可能出错了,因为该Ajax脚本正在404ing。我只是逐字测试了此代码,并且效果很好:
<html>
<head>
<style>
body, html{
height:200%;
}
#one {
width:100%;
height: 200px;
background-color: aqua;
position: fixed;
}
#two {
width: 100%;
height:50px;
background-color: red;
margin-top:150%;
position:absolute;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script>
$(document).ready(function() {
var windw = this;
$.fn.followTo = function ( elem ) {
var $this = this,
$window = $(windw),
$bumper = $(elem),
bumperPos = $bumper.offset().top,
thisHeight = $this.outerHeight(),
setPosition = function(){
if ($window.scrollTop() > (bumperPos - thisHeight)) {
$this.css({
position: 'absolute',
top: (bumperPos - thisHeight)
});
} else {
$this.css({
position: 'fixed',
top: 0
});
}
};
$window.resize(function()
{
bumperPos = pos.offset().top;
thisHeight = $this.outerHeight();
setPosition();
});
$window.scroll(setPosition);
setPosition();
};
$('#one').followTo('#two');
});
</script>
</head>
<body>
<div id="one">FIXED...</div>
<div id="two">...BUT STOPS HERE</div>
</body>
</html>
如果仍然无法正常运行,请检查浏览器中的控制台,您的JavaScript可能在某个地方出现了随机语法错误。将此代码粘贴到文件中将演示jsfiddle所做的相同操作。