我正在尝试在页面滚动到某个点时触发动画。这是我到目前为止所拥有的(Codepen version):
$(window).scroll(function () {
var hT = $('#photoshop').offset().top,
hH = $('#photoshop').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT - wH), wS);
if (wS > (hT + hH - wH)) {
// I need the CSS to happen here, so it happens when the page is scrolled to "photoshop". //
}
});
body {
background-color: black;
}
#photoshop {
font-family: 'Roboto', sans-serif;
color: #FF5444;
text-align: left;
background-color: transparent;
width: 20%;
margin-left: 24%;
margin-bottom: 3px;
padding: 2px;
margin-top: 10px;
padding-left: 3px;
font-size: 80%;
}
/* this is what I need to happen when the page is scrolled to id="photoshop"
#photoshop {
width: 40%;
background-color: #134;
transition: ease-in 400ms;
-moz-transition: ease-in 400ms;
-webkit-transition: ease-in 400ms;
transition-delay: 200ms;
}
*/
.percent {
display: inline;
color: #fff;
margin-right: 3px;
font-size: 80%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="photoshop">
<div class="percent">80%</div> photoshop
</div>
</body>
我已经尝试通过ID函数执行get元素,但是当我需要它时它不会加载css。我对JavaScript知之甚少,并希望尽可能少地编写脚本。有没有办法在if (wS > (hT + hH - wH)) {
行之后更改CSS?
答案 0 :(得分:1)
您可以使用jquery .css()
函数(see docs)。它需要一个json对象,其中包含您要应用的css属性和值。所以你会做这样的事情:
if (wS > (hT + hH - wH)) {
$('#photoshop').css({
'width': '40%',
'background-color': '#134',
'transition': 'ease-in 400ms',
'-moz-transition': 'ease-in 400ms',
'-webkit-transition': 'ease-in 400ms',
'transition-delay': '200ms',
});
}
答案 1 :(得分:1)
尝试下面的内容,
您可以使用jQuery addClass方法,
只需使用 css 创建一个新类,并在视口
中显示div时使用addClass
方法应用该类
$(window).scroll(function() {
var hT = $('#photoshop').offset().top,
hH = $('#photoshop').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT - wH), wS);
if (wS > (hT + hH - wH)) {
$('#photoshop').addClass("photoshop_trans");
}
});
body {
background-color: black;
}
.dummy {
height: 500px;
}
#photoshop {
font-family: 'Roboto', sans-serif;
color: #FF5444;
text-align: left;
background-color: transparent;
width: 20%;
margin-left: 24%;
margin-bottom: 3px;
padding: 2px;
margin-top: 10px;
padding-left: 3px;
font-size: 80%;
}
/* this is what I need to happen when the page is scrolled to id="photoshop" */
#photoshop.photoshop_trans {
width: 40%;
background-color: #134;
transition: ease-in 400ms;
-moz-transition: ease-in 400ms;
-webkit-transition: ease-in 400ms;
transition-delay: 200ms;
}
.percent {
display: inline;
color: #fff;
margin-right: 3px;
font-size: 80%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="dummy"></div>
<div id="photoshop">
<div class="percent">80%</div>photoshop
</div>
</body>