jQuery:addClass只有一次

时间:2015-12-10 16:31:30

标签: javascript jquery html css

我在窗口调整大小上运行addClassremoveClass函数,使用if else语句。标记如下:

$(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');
            }

}

唯一的问题是,当您调整窗口大小时,它会不断添加和删除该类,是否可以运行addClassremoveClass函数一次?任何建议将不胜感激!

1 个答案:

答案 0 :(得分:1)

您可以使用.hasClass

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