开发者

jQuery Plugin/JavaScript: Set body-class with actual URL

I know there are JavaScripts or jQuery pl开发者_如何学运维ugins which set some body classes (e.g. something like that <body class="ff3.5 ff win gecko some-awesome-icons-article-with-100-icons">) I don't know how that is called...? Do you know what I mean and have you a link/name of it? The path to the article set as css-body-class is more important for me than for example the browser or OS.


I think you're asking for code that will extract the "filename" portion of the url path, and set that as a class name on the body element.

If so, then here's the basic idea:

$(document).ready(function() {

    var parts = window.location.pathname.split('/');

    var basename = "default-no-basename";
    if( parts && parts.length ) {
        var idx = parts.length-1;
        if( parts[idx] == '' && parts.length > 1 ) {
            --idx;
        }
        basename = parts[idx];
    }
    //alert("basename: "+basename);
    $(body).addClass( basename );
});

That code simply extracts the portion of the page url following the final slash, and writes it into the class attribute of the body tag. If the url path is a "directory" (ie. it ends with a slash), then it'll use the trailing directory name instead. If the url path is just '/', then it'll default to adding the classname 'default-no-basename'.

Important: The above code does not do anything to ensure that the classname is compliant with the allowed characters in css classnames. So if your url was something like: http://example.com/abc/my-cool-page(with stuff).html, then you're going to have problems, because the css class will be set to "my-cool-page(with stuff).html".

You would therefore want to either ensure that this is never being called on a page that has special chars (like (, ), ., and the [space] character in the above example). Or you'll want to add some checking in to that logic to strip out disallowed chars.

good luck.


If I've understood your query, you need to add a class to certain tag. Using jquery this is how it can be done.

$('body').addClass('anyClass');


I found a JavaScript solution: http://snipt.net/mountainash/javascript-adds-classes-to-body-based-on-url/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜