English 中文(简体)
with classes/J
原标题:Merging css classes with jQuery/Javascript

我有一个问题。 我有一台楼房,大量使用多个剪辑。

<div class="class1 class2 class3">foo</div>

不幸的是,我有一个“浏览器”(因为缺少一个更好的期限),无法以这种方式处理多个课程。

我可在 多级上确定所有要素,但现在我需要创建新的课程,合并这些课程。 第一项尝试是将所有风格划入风格,但速度太慢,无必要地篡改文件。

What I now want to do is find an element with multiple classes. Create a new class which is a combination, and replace the elements class with the newly created one, as well as any other elements with the same class combination.

任何关于如何最好地解决这一问题的想法。

最佳回答

概述:这项职能归还了所有重复类别名称的定购清单,很容易用于合并课堂。

To start off, get a useful list of duplicates:

var multi = {};

$("*[class]").each(function(){
    var class = this.className.replace(/^s+|s+$/g,"").replace(/s+/g,".");
    if(!/./.test(class)) return; //Ignore single classes
    if(multi[class]){
        multi[class]++;
    } else {
        multi[class] = 1;
    }
});

//Now, merge duplicates, because .class1.class2 == .class2.class1
var multi_nodup = {};
for(var classes in multi){
    var a_classes = classes.split(".");
    var a_classes = a_classes.sort();
    var a_classes = a_classes.join(".");
    if(multi_nodup[a_classes]){
        multi_nodup[a_classes] += multi[classes];
    } else {
        multi_nodup[a_classes] = multi[classes]
    }
}
//Now, multi_npdup is a map of all duplicate classnames

var array_multi = [];
for(var classes in multi_nodup){
    array_multi.push([multi_nodup[classes], classes]);
}
array_multi.sort(function(x,y){return y[0]-x[0]});
//array_multi is an array which looks like [["class1.class2.class2", 33],
//             ["class3.class4", 30], ...]
// = A list, consisting of multiple class names, where multiple classnames
// are shown, together with the nuber of occurences, sorted according to
// the frequence

Execute my function, and output variable array_multi. This will show you a map of multiple class names, so that you can replace multiple classnames, accordingly.

由于我储存类别名称的特殊方式,你可以使用<条码>美元”+阵列——多[n][0],查阅所有具有与<条码>中<>m>n第位数相等的一组类别名称的内容。

可读产出实例:

//Overwrites current document!
var list = "";
for(var i=0; i<array_multi.length; i++) list += array_multi[i][0] + "	" + array_multi[i][1];
document.open();
document.write("<pre>"+list+"</pre>")
document.close();

Automatic conversion

一种方法,即把所有不同的类别特性添加到Java 字典中,将其添加到物体上,从而实现分类名称的合并。 这是获得CSS准确特性的最可靠方式,因为试图通过<代码>文件>上的物体获取类别名称可能会产生一些略有不同的结果。 例:

var classStyle = {};
classStyle["class1"] = "border:1px solid #000;";
classStyle["class2"] = "color:red";

//Make sure that each declaration ends with a semicolon:
for(var i in classStyle) if(!/;$/.test(classStyle[i])) classStyle[i] += ";";

//Initialise
var all_styles = {};
for(var i=0; i<array_multi.length; i++){
    all_styles[array_multi[i][1]] = "";
}

//This loop takes definition precedence into account
for(var currentCName in classStyle){
    var currentClass = new RegExp("(?:^|\.)" + currentCName + "(?:\.|$)");

    // Rare occasion of failure: url("data:image/png,base64;....")
    var separateProps = classStyle[currentCName].split(";");
    var prop_RE = {};
    for(var p=0; p<separateProps.length; p++){
        var cssProperty = separateProps[p];
        if(!/:/.test(cssProperty)) continue; //Invalid CSS property
        prop_RE[cssProperty] = new RegExp("(^|;)\s*" + cssProperty.match(/(S+)s*:/gi)[1] + "\s*:[^;]+;?", "gi");
    }

    for(var class in all_styles){
        if(currentClass.test(class)){
            for(var k in prop_RE){
                all_styles[class] = all_styles[class].replace(prop_RE[k],"$1") + k;
            }
        }
    }
}

//To finish off:
var allClassesToString = "";
for(var class in all_styles){
    var newClass = class.replace(/./g, "_");
    $("."+class).each(function(){
        this.className = newClass;
    });
    allClassesToString += "."+newClass + "{" + all_styles[class] + "}
";
}

// allClassesToString <------- This variable now holds a string of all duplicate CSS classes!
//Example:
var style = $("<style>");
style.text(allClassesToString);
style.appendTo($("head:first"));
问题回答

Loop through all tags. Split the class names into an array. Sort it to get it into a predictable order. Join the string back together.

$(document).ready(function() {
    var classList = {};
    $("*").each(function() {
        var temp;
        if (this.className) {
            temp = this.className.split(" "); // split into array
            temp.sort();                      // put in predictable order
            this.className = temp.join("");   // put class name back without spaces
            classList[this.className] = true; // add to list
        }
    });
    // classList object contains full list of all classNames used
});

FYI, it seems really odd that you d have a browser that supports jQuery, but doesn t support CSS styles for multiple class names. You do realize that you are going to have to supply completely different stylesheets that work off the concatenated names, right? And, if you can change the stylesheets, it makes me wonder why you can t change the HTML.

工作执行:http://jsfiddle.net/jLG00/uPET7/





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签