滚动仅在值上添加类

时间:2016-08-03 13:41:50

标签: javascript jquery

我偶然发现了一个问题,我想通过在滚动超过特定值时添加“打开”类来打开菜单。问题是我希望它在该值之后只打开ONCE,因此它对用户来说是显而易见的,然后由用户通过切换来打开和关闭它。

我使用了这种方法:

<script type="text/javascript">
jQuery(function() {
    //caches a jQuery object containing the header element
    jQuery(window).scroll(function() {
        var scroll = jQuery(window).scrollTop();

        if (scroll >= 1150) {
            jQuery(".menubar").addClass("open");

        }
    });
});
</script>

问题是在1150值之后,它会在此值内的每次滚动后不断弹出。 如何让它停止并使此事件只发生一次?

提前谢谢!

2 个答案:

答案 0 :(得分:4)

检查班级是否已存在。如果类更改太容易,请使用变量:

var isOpened = false;

jQuery(function() {
    //caches a jQuery object containing the header element
    jQuery(window).scroll(function() {
        var scroll = jQuery(window).scrollTop();

     // The original if statement, testing for `.hasClass()`
     // if (scroll >= 1150 && !$(".menubar").hasClass()) {

        if (scroll >= 1150 && !isOpened) {
            isOpened = true;
            jQuery(".menubar").addClass("open");

        }
    });
});

答案 1 :(得分:0)

您可以设置一个标志,然后只检查该标志。

var deserialized = JsonConvert.DeserializeObject<JObject>(json);
var locations = (
    from state in deserialized.Properties().Select(v => v.Value).OfType<JObject>()
    from city in state.Properties().Select(v => v.Value).OfType<JArray>()
    from location in city
    select new Location
    {
        Name = location.Value<string>("Name"),
        Address = location.Value<string>("Address"),
        City = location.Value<string>("City"),
        State = location.Value<string>("State"),
        Zip = location.Value<string>("Zip")
    }).ToList();
相关问题