浮动的公告——jQuery简单实现

界面:


head:

 

  1.  <title>浮动公告</title>  
  2. <script src="js/jquery.js" type="text/javascript"></script>  
  3. <link href="css/ExatMan.css" rel="stylesheet" type="text/css" />  

body:

  1. <div id="examInfo" runat="server">  
  2.        欢迎使用在线考试系统  
  3.        <hr />  
  4.        <asp:Label ID="lblStudentName" runat="server"></asp:Label>  
  5.        <hr />  
  6.        剩余时间:  
  7.        <asp:TextBox ID="txtTime" runat="server" Enabled="False"></asp:TextBox>  
  8.        <hr />  
  9.        请同学认真阅读考试须知:  
  10.        <br />  
  11.        <asp:Label ID="lblExaminationInstruction" runat="server" ForeColor="Red"></asp:Label>  
  12.        <br />  
  13.        <hr />  
  14.    </div>  

JavaScript:

  1. <script type="text/javascript">  
  2.         $(function () {  
  3.              //根据id选择器定义examInfo的jQuery对象  
  4.             var $sidebar = $("#examInfo"),  
  5.             $window = $(window),  
  6.             //获取examInfo在当前窗口的相对偏移  
  7.             offset = $sidebar.offset(),  
  8.             //自定义,作为偏移量  
  9.             topPadding = 15;  
  10.             //绑定滚动事件  
  11.             $window.scroll(function () {  
  12.                     if ($window.scrollTop() > offset.top) {  
  13.                             //判断当前位置,如果相对于滚动条顶部偏移大于对窗口的偏移量,调整外上边距  
  14.                             $sidebar.stop().animate({  
  15.                                 //重新定位examInfo  
  16.                                         marginTop: $window.scrollTop() - offset.top + topPadding  
  17.                                 });  
  18.                         } else {  
  19.                                 //如果当前如果相对于滚动条顶部偏移小于对窗口的偏移量,外上边距为零  
  20.                                 //自定义动画,指定的属性必须用骆驼形式  
  21.                                 $sidebar.stop().animate({  
  22.                                         marginTop: 0  
  23.                                 });  
  24.                         }  
  25.                 });  
  26.         });  
  27.         </script>  

运行结果:公告可以随着滚动条的移动动态定位到页面左上部分。

posted @ 2014-07-27 09:05  阳光小屋  阅读(339)  评论(0编辑  收藏  举报