在滚动和悬停时更改标题背景

时间:2018-09-24 14:30:18

标签: javascript jquery html css

我遇到了问题,需要一些帮助。

我试图在悬停和滚动时更改标题背景颜色。我有scroll部分,但没有hover部分。我一直遇到问题。

您对此有解决方案吗?

// function checkNav() {
// if($('header').hasClass('blue-head') === false) {
//  $('header').hover(function() {
//  $(this).addClass('white-head');
//  $('.logo img').attr('src','/wp-content/uploads/2018/09/Asset-1tempur-ped.png');
//  }, function() {
//  $(this).removeClass('white-head');
//  $('.logo img').attr('src','/wp-content/uploads/2018/09/white-logo.png');
//  });
// } else {
//  $('.logo img').attr('src','/wp-content/uploads/2018/09/Asset-1tempur-ped.png');
// }
// }
$(document).ready(function() {
    $(window).on("scroll", function() {
        if($(window).scrollTop() > 50) {
            $("header").addClass("blue-head");
            $('.logo img').attr('src','/wp-content/uploads/2018/09/Asset-1tempur-ped.png');

        } else {
            //remove the background property so it comes transparent again (defined in your css)
            $("header").removeClass("blue-head");
            $('.logo img').attr('src','/wp-content/uploads/2018/09/white-logo.png');
    }
    });
});

1 个答案:

答案 0 :(得分:1)

通过使用toggleClass可以更改悬停颜色。如果不占用标题,则可以以相同的方式切换徽标。在代码段中,我将图像设置为背景图像..简单但有效。

祝你好运

$(document).ready(function() {
  if ($('header').hasClass('blue-head')) {
    $('header').hover(function() {
      $('header').toggleClass('blue-head').addClass('white-head');
    });
  }
});
body {
  height: 100%;
}

.white-head {
  background-color: white;
  text-transform: capitalize;
  text-align: center;
  color:white;
 font-weight:600;
  /* background-image: url('/wp-content/uploads/2018/09/white-logo.png');*/
 background-image:url('http://cairngorms.co.uk/wp-content/uploads/2017/07/A-father-and-son-cycling-a-country-path-Ballater.-The-Cairngorms-National-Park1.jpg');
 background-size: cover;
 background-repeat:no-repeat;
}

.blue-head {
  background-color: blue;
  text-transform: uppercase;
  text-align: left;
  background-image: url('/wp-content/uploads/2018/09/Asset-1tempur-ped.png');
}

header {
  height: 50px;
}

div {
  height: 100px;
  background-color: yellow;
}

footer {
  min-height: 200px;
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <header class="blue-head">
    header

  </header>
  <div>

  </div>
  <footer>

  </footer>

</body>