我有一个div #HangerLeft,它的css.right是通过jQuery自动生成的,它基于正文宽度位于页面的左侧。它是绝对定位的。
function hangerLeft() {
var hangerPosition = (jQuery("body").innerWidth() / 2) + (990 / 2);
jQuery("#HangerLeft").css("position","absolute").css("right", hangerPosition +"px").css("top","20px");
}在#HangerLeft div中,我有一个没有定位的#scrollWrapper div,在#scrollWrapper中,我有一个#scrollBox。#scrollBox是绝对定位的。
#scrollWrapper { width:130px; height:400px; border:1px solid #fff;}
#scrollBox { position: absolute; top: 100; margin-top: 25px; padding-top: 0px;}
#scrollBox.fixed { position: fixed; top: 0;}在滚动之前,#scrollBox将一直保持不动。滚动过#scrollBox div的顶部后,javascript会添加一个类,使#scrollBox position:fixed而不是绝对位置。
<script>
$(function () {
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
var top = $('#scrollBox').offset().top - parseFloat($('#scrollBox').css('margin-top').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= top) {
// if so, ad the fixed class
$('#scrollBox').addClass('fixed');
} else {
// otherwise remove it
$('#scrollBox').removeClass('fixed');
}
});
}
});
</script>在Firefox和IE中,这工作得很好。
在Safari和Chrome中,一旦#scrollBox javascript命中,#scrollBox div就会从#HangerLeft div跳到页面中间,并忽略#HangerLeft div的位置。
我已经和这个问题斗争了两个星期了,现在我很迷茫。
任何帮助都将不胜感激。
发布于 2010-09-14 08:27:24
好的,我修改了你的代码。我把它放在你喜欢的地方..我会用一种不同的方式来设置,但这适用于您的方法。您可以看到一个live version here JavaScript:
<script type="text/javascript">
function setupScrollBox(){
// cache box element and use wrapper as your position element
var hanger = $("#HangerLeft"),
position = $("#wrap").offset();
hanger.css({
position: 'absolute',
left: position.left - $("#scrollWrapper").outerWidth(),
marginTop: '25px'
});
}
$(document).ready(function(){
// check if IE6
var msie6 = $.browser.msie && $.browser.version < 7;
setupScrollBox();
// attach resize event to window
$(window).resize(function(){
setupScrollBox();
});
// check browser
if(!msie6){
// attach scroll event
$(window).scroll(function (event) {
// get scroll position and cache element so we only access it once
var y = $(this).scrollTop(),
wrap = $('#HangerLeft');
// if scroll position is greater than 100 adjust height else do nothing
if(y > 100)
// you can animate the position or not, your call
wrap.stop().animate({top: y}, 250);
//wrap.css('top', y+'px');
});
}
});
</script>CSS:
#HangerLeft {
top: 100px;
}
#scrollWrapper {
width: 130px;
}
#scrollBox {
position: relative;
margin-top: 25px;
padding-top: 0px;
z-index: 10;
}HTML:
<div id="HangerLeft">
<div id="scrollWrapper">
<div id="scrollBox">
<div id="mainContainer">
<div id="shareContainer">
<div class="moduleShareHeader">SCROLL BOX</div>
</div>
</div>
</div>
</div>
</div>https://stackoverflow.com/questions/3705244
复制相似问题