使用jQuery增加或减少类名

时间:2015-05-06 22:37:41

标签: javascript jquery css materialize

我正在使用Materialise CSS(http://materializecss.com/)框架,该框架(确实是一个充满臃肿的样式表)的颜色类名;类名遵循逻辑:

.blue {}
.blue.darken-1 {}
.blue.lighten-1 {}

“变暗”和“减轻”1-5的增量。我正在尝试编写一个在悬停时增加类的函数;因为有些元素会有一个颜色名称类(blue)而其他元素会有一个颜色名称和一个“变暗”或“变亮”的修饰符类(即blue lighten-3),我采用了使用indexOf搜索元素的类。不过,我不禁感到这种方法效率低下且笨重。有什么想法吗?

function darkenClass(theclasses, theelem) {
    var gotclass = theclasses;
    var gotelem = theelem;
    if (gotclass.indexOf('darken-1') > -1) {
        gotelem.attr("class", "").attr("class", gotclass.replace("darken- 1", "darken-2"));
    } else if (gotclass.indexOf('darken-2') > -1) {
        gotelem.attr("class", "").attr("class", gotclass.replace("darken-2", "darken-3"));
    } else if (gotclass.indexOf('darken-3') > -1) {
        gotelem.attr("class", "").attr("class", gotclass.replace("darken-3", "darken-4"));
    } else if (gotclass.indexOf('darken-4') > -1) {
        gotelem.attr("class", "").attr("class", gotclass.replace("darken-4", "darken-5"));
    } else if (gotclass.indexOf('lighten-5') > -1) {
        gotelem.attr("class", "").attr("class", gotclass.replace("lighten-5", "lighten-4"));
    } else if (gotclass.indexOf('lighten-4') > -1) {
        gotelem.attr("class", "").attr("class", gotclass.replace("lighten-4", "lighten-3"));
    } else if (gotclass.indexOf('lighten-3') > -1) {
        gotelem.attr("class", "").attr("class", gotclass.replace("lighten-3", "lighten-2"));
    } else if (gotclass.indexOf('lighten-2') > -1) {
        gotelem.attr("class", "").attr("class", gotclass.replace("lighten-2", "lighten-1"));
    } else {
        gotelem.addClass("darken-1");
    }
}

2 个答案:

答案 0 :(得分:1)

// freezes the amount col as well...
$('#SetGrid2').on('click', function(){
   jQuery("#sg2")
   .jqGrid('destroyFrozenColumns')
   .jqGrid('setColProp','amount', {frozen:true})
   .jqGrid('setFrozenColumns')
   .trigger('reloadGrid', [{current:true}])
});

答案 1 :(得分:0)

一种方法使用html元素的数据属性:

HTML:

<div class="darken-3" data-darken="3"><!-- ... --></div>
<div class="lighten-2" data-lighten="2"><!-- ... --></div>
<!--  etc -->

JS:

function darkenClass(theclasses, theelem) {
    var n_dark
      , n_light
      ;

    n_dark  = parseInt($(theelem).attr('data-darken')) || 0;
    n_light = parseInt($(theelem).attr('data-lighten')) || 0;
    if ((n_dark > 0) && (n_dark < 5)) {
       $(theelem).removeClass('darken-' + n_dark );
       n_dark++;
       $(theelem).attr('data-darken', n_dark);
       $(theelem).addClass('darken-' + n_dark);
    }
    else {
       if ((n_light < 6) && (n_light > 1)) {
          $(theelem).removeClass('lighten-' + n_light );
          n_light--;
          $(theelem).attr('data-lighten', n_light );
          $(theelem).addClass('lighten-' + n_light );
       }
       else {
          $(theelem).addClass('darken-1' );
       }
    }
}