纯JavaScript - 如何将类添加到类中?或者在课堂上改变风格

Leo*_*ban 0 javascript css

我有.tag一个以点击/ mousedown操作命名的几个类,我想要更改clear:bothclear:none所有.tag项目.或者将类添加.clearNone { clear:none; }到所有标记中.

到目前为止我没有运气的尝试:

function mouseDown(e) {
    window.addEventListener('mousemove', sizePanel, true);

    // Using ID works
    var tagsCol = document.getElementById("tags-col");
    tagsCol.classList.add("width100");

    // Using class does not
    var tag = document.getElementsByClassName("tag");
    tag.classList.add("clearNone");
};
Run Code Online (Sandbox Code Playgroud)

CSS

.tag {
    overflow: hidden;
    float: left;
    position: relative;
    margin: 0 10px 10px 0;
    padding: 5px 10px;
    width: auto;
    cursor: pointer;
    clear: both;
    @include rounded(4px);
}

.clearNone  { clear: none; }
Run Code Online (Sandbox Code Playgroud)

你会怎么做到这一点?注意,有上百.tag

SLa*_*aks 5

不要那样做.

相反,将标记类名添加到公共祖先元素,然后使用CSS规则:

.SomeClassName .tag {
    clear: both;
}
Run Code Online (Sandbox Code Playgroud)