【问题标题】:Is there a way to add a smooth/ease transition effect to jQuery?有没有办法为 jQuery 添加平滑/轻松的过渡效果?
【发布时间】:2016-04-14 20:18:50
【问题描述】:

当用户将页面滚动到页面的某个位置时,我有这段代码可以修改页面上元素的位置:

<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效果触发时给这个添加类似于CSStransition: all 0.5s ease的效果?

【问题讨论】:

  • 你真的应该使用 JQuery 的 'css' 属性而不是添加样式属性
  • 你不能使用 CSS 属性来添加 !important
  • 你可以使用 jquery 的 .animate 函数,但我不确定它是否会让你添加 !important 属性!
  • 你可以很容易地做到这一点,而不需要 jQuery 缓动。只需通过 CSS 将transition: all 0.5s ease 添加到#tab_toggle #tab_toggle_bg,它就会产生缓动效果。 Here 是从 Varun 的小提琴中提取的样本。
  • @Harry 绝对正确!你应该把这个作为答案:) 我想知道为什么我不考虑尝试这个

标签: javascript jquery css css-transitions transition


【解决方案1】:

只要您有权访问 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2019-09-16
    • 2015-10-22
    • 1970-01-01
    • 2014-03-05
    • 2013-07-07
    • 1970-01-01
    相关资源
    最近更新 更多