最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: addClass only once - Stack Overflow

programmeradmin1浏览0评论

I have an addClass and removeClass function running on window resize, using an if else statement. The markup is as follows:

$(window).load(function() {
  resize();
});

//Every resize of window
$(window).resize(function() {
  resize();
});

//Dynamically assign height
function resize() {
  // Handler for .ready() called.
    var windowWidth = $(window).width(),
        windowHeight = $(window).height(),
        windowHeight = windowWidth / 1.7777;

        var loadwindowHeight = $(window).height(),
            loadspriteHeight = $('.spritespin-canvas').height();

            if(loadspriteHeight < loadwindowHeight) {
                $('.spritespin-canvas').addClass('height');
            } else {
                $('.spritespin-canvas').removeClass('height');
            }

}

The only problem is, when you resize the window, it keeps repeatedly adding and removing the class, it it possible to run the addClass and removeClass functions once? Any suggestions would be greatly appreciated!

I have an addClass and removeClass function running on window resize, using an if else statement. The markup is as follows:

$(window).load(function() {
  resize();
});

//Every resize of window
$(window).resize(function() {
  resize();
});

//Dynamically assign height
function resize() {
  // Handler for .ready() called.
    var windowWidth = $(window).width(),
        windowHeight = $(window).height(),
        windowHeight = windowWidth / 1.7777;

        var loadwindowHeight = $(window).height(),
            loadspriteHeight = $('.spritespin-canvas').height();

            if(loadspriteHeight < loadwindowHeight) {
                $('.spritespin-canvas').addClass('height');
            } else {
                $('.spritespin-canvas').removeClass('height');
            }

}

The only problem is, when you resize the window, it keeps repeatedly adding and removing the class, it it possible to run the addClass and removeClass functions once? Any suggestions would be greatly appreciated!

Share Improve this question asked Dec 10, 2015 at 16:31 user1374796user1374796 1,58213 gold badges46 silver badges76 bronze badges 2
  • 1 use hasClass('height') to check api.jquery./hasclass – Sean Wessell Commented Dec 10, 2015 at 16:35
  • use $(window).one('resize',func.. instead of $(window).resize(func.. – Vixed Commented Dec 10, 2015 at 16:42
Add a ment  | 

1 Answer 1

Reset to default 5

You can use .hasClass.

var hasHeightClass = $('.spritespin-canvas').hasClass('height');
if (loadspriteHeight < loadwindowHeight && !hasHeightClass) {
    $('.spritespin-canvas').addClass('height');
} else if (hasClass) {
    $('.spritespin-canvas').removeClass('height');
}
发布评论

评论列表(0)

  1. 暂无评论