当用户将页面滚动到页面的某个位置时,我有这段代码来修改页面上元素的位置:
<script type="text/javascript">
jQuery(window).scroll(function() {
if(jQuery(window).scrollTop() > 150) {
jQuery("#tab_toggle #tab_toggle_bg").attr("style","top: 45% !important");
} else {
jQuery("#tab_toggle #tab_toggle_bg").removeAttr("style");
}
});
</script>
当scrollTop效果触发时,有没有办法向CSS transition: all 0.5s ease
添加类似的效果?
答案 0 :(得分:2)
只要您可以访问CSS文件并允许对其进行编辑,实现缓动效果的最简单方法是通过CSS向元素添加所需的transition
设置。通过CSS添加到元素的任何转换设置仍将适用于通过JavaScript完成的属性更改。
jQuery(window).scroll(function() {
if (jQuery(window).scrollTop() > 50) {
jQuery("#tab_toggle #tab_toggle_bg").attr("style", "top: 45% !important");
} else {
jQuery("#tab_toggle #tab_toggle_bg").removeAttr("style");
}
});
#tab_toggle {
width: 100%;
height: 500px;
position: relative;
}
#tab_toggle_bg {
position: absolute;
background: red;
color: white;
text-align: center;
line-height: 140px;
width: 140px;
height: 140px;
top: 0%; /* an initial value for the property that needs to be transitioned is also required */
transition: all 0.5s ease; /* add the required timing function - ease, ease-in, ease-in-out, linear */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tab_toggle">
<div id="tab_toggle_bg">
Scroll the page for more than 50px.
</div>
</div>