滚动后更改对象颜色

时间:2015-06-28 06:28:27

标签: javascript jquery html

我想要一个可以在滚动(向下)100px后改变颜色的对象,并在向后滚动(向上)后更改回默认值。我正在使用此代码但不能正常工作

jQuery的:

$(window).scroll(function() {

//After scrolling 100px from the top...
if ( $(window).scrollTop() >= 100 ) {
$('#menu').css('background', '#fff');

//Otherwise remove inline styles and thereby revert to original stying
} else {
$('#menu').removeAttr('style');

}
});​

和我的HTML:

<body>
<table>
<tr>
<td  id="menu" class="title">
TITLE
</td>
<td style="width:40px;">
<div class=" ico">    
<img src="search.svg" alt="search" style="width: 25px;" />
</div>
</td>
<td style="width: 40px;">
<div class=" ico">
<img src="menu.svg" alt="search" style="width: 25px;"/>
</div>
</td>
</tr>
</table>
</body>

2 个答案:

答案 0 :(得分:1)

你走了:

$(function(){
  var navColors = ['red', 'blue'];

  var changeNavState = function(nav, newStateIndex) {
    nav.data('state', newStateIndex).stop().css({
      backgroundColor : navColors[newStateIndex]
    });    
  };

  var boolToStateIndex = function(bool) {
    return bool * 1;    
  };

  var maybeChangeNavState = function(nav, condState) {
    var navState = nav.data('state');
    if (navState === condState) {
      changeNavState(nav, boolToStateIndex(!navState));
    }
  };

  $('#header_nav').data('state', 1);

  $(window).scroll(function(){
    var $nav = $('#header_nav');

    if ($(document).scrollTop() > 100) {
      maybeChangeNavState($nav, 1);
    } else {
      maybeChangeNavState($nav, 0); 
    }
  });
});

http://jsfiddle.net/2rqp6r6z/

答案 1 :(得分:0)

我正在使用此代码进行棒顶菜单 你可以为自己定制它,如果你不能说,那我就改变它自己,但如果你,你自己做的更好

   <script>
$('.top-menu').addClass('original').clone().insertAfter('.top-menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();

scrollIntervalID = setInterval(stickIt, 10);


function stickIt() {

  var orgElementPos = $('.original').offset();
  orgElementTop = orgElementPos.top;               

  if ($(window).scrollTop() >= (orgElementTop)) {
    orgElement = $('.original');
    coordsOrgElement = orgElement.offset();
    leftOrgElement = coordsOrgElement.left;  
    widthOrgElement = orgElement.css('width');

    $('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement+'px').show();
    $('.original').css('visibility','hidden');
  } else {
    $('.cloned').hide();
    $('.original').css('visibility','visible');
  }
}
</script>