1

我在 div 中有一个窄而长的图像轮播,它位于页眉和顶部菜单栏下方的页面右侧。如果我的页面有很多内容并且比 iamge 的高度长得多,我希望图像以下列方式定位:

  • 页面上的相对或绝对位置,直到图像顶部距离窗口顶部 10px
  • 固定位置,以便在阅读主页内容时保持在视图中。
  • 到达页面底部后的相对或绝对位置,以便 div 占据页脚上方与页面其余部分一致的位置。div不应与页脚发生冲突,不应有很大的差距。

我尝试了许多查看位置变量的变体,例如:

jQuery(document).ready(function(){  
     $(window).scroll(function () {  

 var y = $('#rightbackground').offset().top - $(window).scrollTop();
 var z = $(document).Height - $('#rightbackground').offset().top - $('#rightbackground').Height();

   if (y < 10 && z > 0) {$('#rightbackground').removeClass('content-stay2');  
            $('#rightbackground').addClass('content-scroll2');  

        } 

        else {  
            $('#rightbackground').addClass('content-stay2');  
            $('#rightbackground').removeClass('content-scroll2');  
        }  
    });       

}); 

但达不到我想要的效果。

HTML(来自评论):

<div id="rightbackgroundcontainer"> 
  <div id="rightbackground"> 
    <div id="mainright"> 
      <div id="comslider_in_point_53815"></div> 
<script type="text/javascript"> 
  var oCOMScript53815=document.createElement('script');     
  oCOMScript53815.src="comslider53815/comsliderd.js?timestamp=1381081498"; 
  oCOMScript53815.type='text/javascript'; 
  document.getElementsByTagName("head").item(0).appendChild(oCOMScript53815); 
</script> 
      <div id="bottomrighttxt"> 
        <h2><span class="greytext">Industry News</span></h2> 
      </div>
    </div> 
  </div> 
</div>

CSS(也来自评论):

.content-stay2 {position: relative; } 
.content-scroll2 { 
  position: fixed; 
  float: left; 
  margin-left: 642px; 
  margin-top: -300px;
}

谢谢

4

1 回答 1

0

The rough solution for what you want is following. Instead of trying to locate your object at the page, place two anchors in your HTML:

<a id='top'></a> // at top of the page right before your object
<a id='bottom'></a> // before the page footer

Then your jQuery function would position your object based on the position of two static anchors that you place on your page. Here is the function:

$(window).scroll(function(){
    var top = $('#top').position().top()-10;
    var bottom = $('#bottom').position().top();
    var bottom_of_object = $('#rightbackground').position().top + 
        $('#rightbackground').height();
if (bottom <= bottom_of_object) // //when object hits footer
    {
        //your CSS to position it above footer anyway you want
        });
    } else if (top <= 0) //when object hits  the top of the window
    {
       $('#rightbackground').css({
        'position':'fixed',
         'top': '10px'
         })
    } else { // when the page scrolled to the top
       // your default CSS rules for your object
    }
})

And check position of those anchors relative to user's view point. Based on this you can position your element the way you want.

于 2013-10-16T22:51:54.140 回答