简体   繁体   English

有没有一种方法可以向jQuery添加平滑/轻松过渡效果?

[英]Is there a way to add a smooth/ease transition effect to jQuery?

I have this code to modify the position of an element on my page when user scrolls page a certain position of the page: 当用户将页面滚动到页面的某个位置时,我可以使用以下代码来修改元素在页面上的位置:

<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>

Is there a way to add an effect similar to the CSS transition: all 0.5s ease to this when the scrollTop effect triggers? 有没有一种方法可以添加类似于CSS transition: all 0.5s ease的效果transition: all 0.5s ease当scrollTop效果触发时, transition: all 0.5s ease实现?

As long as you have access to the CSS file and are allowed to edit it, the simplest way to achieve the easing effect would be to add the required transition setting to the element via CSS. 只要您有权访问CSS文件并允许对其进行编辑,实现缓动效果的最简单方法就是通过CSS向元素添加所需的transition设置。 Any transition setting that is added to the element via CSS will remain applicable for property changes done through JavaScript also. 通过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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM