我有一个元素,我试图在页面滚动时使用jQuery动画。我试图让元素的背景颜色从透明变为黑色。我一直在尝试不同的方法来解决这个问题,但它们都没有奏效。请帮忙。
$(window).scroll(function() {
if ($(window).scrollTop() >= 100) {
$("#heading").animate({
backgroundColor: "rgb(10,22,18,0)"
}, "slow");
} else {
$("#heading").animate({
backgroundColor: "rgb(10,22,18,1)"
}, "slow");
}
});
#heading {
z-index: 2;
position: fixed;
height: 30px;
border: none;
background-color: rgb(10, 22, 18, 0);
}
.head {
display: inline;
float: left;
opacity: 1.0;
}
.head2 {
height: 30px;
width: auto;
padding-left: 5px;
padding-right: 5px;
text-align: center;
text-shadow: 1px 1px 3px #666666;
color: rgb(255, 255, 255);
font-size: 15px;
text-decoration: none;
border: none;
background: none;
}
.head2:hover {
color: rgb(255, 255, 255);
text-decoration: none;
background-color: rgb(0, 0, 0);
}
.font {
font-family: 'Raleway', sans-serif;
font-style: normal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="heading">
<img class="head" id="mainImg" src="Images/logo.png" alt="Know Music">
<button class="head head2 font" href="" id="hb1">Guitar</button>
<button class="head head2 font" href="" id="hb2">Bass</button>
<button class="head head2 font" href="" id="hb3">Piano</button>
<button class="head head2 font" href="" id="hb4">Drums</button>
</div>
答案 0 :(得分:2)
我向JS添加了一个条件,一旦它大于100就添加一个类,并在它下面删除该类。我试过toggleClass,但它是闪烁的。我在css上添加了const sum = responseArray.reduce((currentSum, nextObject) => {
// Note that you need to coerce points_earned
// to a Number or it will simply concatenate the strings
return currentSum + +nextObject.points_earned;
// 0 is your initial value used by currentSum in
// the first iteration
}, 0);
类来进行背景颜色更改,并添加了到.change
ID的转换。
JSFiddle除非使用插件,否则无法使用jQuery中的animate函数对backgroundColor进行动画处理。见jQuery animate docs
#heading
&#13;
$(window).scroll(function() {
if ($(window).scrollTop() >= 100) {
$("#heading").addClass(" change");
} else{
$("#heading").removeClass(" change");
}
});
&#13;
html,body{height:3000px;}
#heading {
z-index: 2;
position: fixed;
height: 30px;
border: none;
background-color: rgb(10, 22, 18, 0);
transition: 0.5s ease-in-out all;
}
.head {
display: inline;
float: left;
opacity: 1.0;
}
.head2 {
height: 30px;
width: auto;
padding-left: 5px;
padding-right: 5px;
text-align: center;
text-shadow: 1px 1px 3px #666666;
color: rgb(255, 255, 255);
font-size: 15px;
text-decoration: none;
border: none;
background: none;
}
.head2:hover {
color: rgb(255, 255, 255);
text-decoration: none;
background-color: rgb(0, 0, 0);
}
.font {
font-family: 'Raleway', sans-serif;
font-style: normal;
}
.change{
background-color: rgba(10,22,18,1);
}
&#13;
答案 1 :(得分:0)
试试这个
$(window).scroll(function(){
if($(this).scrollTop()>= 100){
// animate
}else{
// animate
}
});