javascript - 滚动 500px 后的 Jquery addclass

标签 javascript jquery html addclass scrolltop

我想在使用 jquery 将页面向下滚动 500 像素后向 div 添加一个类。我找到了一种方法,但它是一个即时转换,我希望能够控制添加类所需的时间,就像使用普通的 Jquery addclass 一样。

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();
    if (scroll >= 500) {
        $(".nav").addClass("navnewclass");
    }
});

我试过这样做:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();
    if (scroll >= 500) {
        $(".nav").addClass("navnewclass", 2000);
    }
});

但它是一样的。

最佳答案

I want to be able to controll how long it takes to add the class like with the normal Jquery addclass.

addClass总是瞬时的,它不是动画套件的一部分。

有些插件可以为您制作基于类的动画(最著名的是 jQuery UI's addClass override ),但 jQuery 本身不会。只需将 jQuery UI 添加到您的页面即可使您的第二个示例正常工作。但也有其他选择。

您的选择是使用这些插件之一,或直接为属性设置动画(使用 animate )而不是使用类。请注意,jQuery 仅对某些类型的属性进行动画处理(尤其不是颜色——jQuery UI 也添加了对动画颜色的支持)。

这是一个使用 jQuery UI 为类(带有颜色)设置动画的示例:Live Copy | Live Source

<style>
.testing {
  color: white;
  background-color: blue;
}
</style>

<!-- ...and later in the body... -->

<p>After half a second, the div below will spend two seconds animating the addition of a class.</p>
<div class="nav">This is a test .nav element</div>
<script>
setTimeout(function() {
    $(".nav").addClass("testing", 2000);
}, 500);
</script>

关于javascript - 滚动 500px 后的 Jquery addclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18288771/

相关文章:

javascript - 使用 HTML5 和 JavaScript 在 SQLite 中插入和检索 BLOB 图像

javascript - 区分单击与 mousedown/mouseup

php - jQuery Blueimp 上传插件的自定义 $options 目录?

html - 如何在 HTML 中为图像添加边框?

php - 如何处理大量重复的 HTML 代码

javascript - 调用两个同名函数

javascript - 如何将 JS Flow 类型与 Redux reducer 和 lodash 结合使用?

jquery - Kendo DropDownList 更改事件

javascript - 无法让 console.log() 在 popup.js 中工作

javascript - CORS AJAX 请求到 Chrome 中本地 WSGI 服务器的延迟过高