10 января 2008 ~ 3791 Комментарий

Css-хак под любой браузер — легко!

css

Обычно я не беру материалы с популярных источников, не читать же моим читателям одно и тоже по сто раз, но это будет исключение, не могу удержатся поделится с остальными такой полезной вещью.

С помощью этого хака можно будет изменять вид вашего сайта(редактируемой странички) для любого браузера и любой ОС в отдельности.

Смотрим код:

<script type="text/javascript">
  var cssFix = function(){
  var u = navigator.userAgent.toLowerCase(),
  addClass = function(el,val){
    if(!el.className) {
      el.className = val;
    } else {
      var newCl = el.className;
      newCl+=(" "+val);
      el.className = newCl;
    }
  },
  is = function(t){return (u.indexOf(t)!=-1)};
  addClass(document.getElementsByTagName('html')[0],[
    (!(/opera|webtv/i.test(u))&&/msie (\d)/.test(u))?('ie ie'+RegExp.$1)
      :is('firefox/2')?'gecko ff2'
      :is('firefox/3')?'gecko ff3'
      :is('gecko/')?'gecko'
      :is('opera/9')?'opera opera9':/opera (\d)/.test(u)?'opera opera'+RegExp.$1
      :is('konqueror')?'konqueror'
      :is('applewebkit/')?'webkit safari'
      :is('mozilla/')?'gecko':'',
    (is('x11')||is('linux'))?' linux'
      :is('mac')?' mac'
      :is('win')?' win':''
  ].join(" "));
}();
</script>

 

Думаю после просмотра кода Вы поняли в чем суть этого скрипта.

Изменять css свойства для разных браузеров мы будем с помощью следующих css классов:

Классы ОС:

  • .win - Windows
  • .linux - Linux
  • .mac - MacOS

Ricky Gervais Live 2: Politics on dvd  

Классы браузеров:

  • .ie - все версии ИЕ
  • .ie8 - ИЕ 8.х
  • .ie7 - ИЕ 7.x
  • .ie6 - ИЕ 6.x
  • .ie5 - ИЕ 5.x
  • .gecko - все версии фаерфокса, и остальные гекко-браузеры
  • .ff2 - фаерфокс 2
  • .ff3 - фаерфокс 3
  • .opera - все версии оперы
  • .opera8 - опера 8.x
  • .opera9 - опера 9.x
  • .konqueror - konqueror
  • .safari - сафари

 

К примеру на нужно изменить цвет шрифта для третьей версии Firefox запущенной под Windows.

.win .ff3 {

color: #000000;

}

На мой взгляд, просто и гениально. Единственный минус этого способа — javascript, так что все юзеры с отключенным javascript'ом отсекаются.

Используйте на здоровье! ;-)

3791 Комментарий для “Css-хак под любой браузер &amp;mdash; легко!”

  1. Альберт 10 июля 2008 at 18:49 Permalink

    Спасибо

  2. Sam 10 июля 2008 at 19:06 Permalink

    Особенно радует «Написал Я собственной персоной» ;)

  3. Я собственной персоной 10 июля 2008 at 19:32 Permalink

    Особенно радует «Написал Я собственной персоной» ;)

    Подумываю убрать этот кусочек кода в вордпресс.
    Тогда никого это не будет радовать (-:
    Приеду — уберу.

  4. Jman 10 июля 2008 at 20:42 Permalink

    Эмм, а мне казалось, что когда откуда-то берут статью, ставят ссылку а источник :)
    Я когда на хабре прочитал, еле удержался от копипаста :)

  5. aratak 10 июля 2008 at 20:45 Permalink

    а ссылку на хабраисточник? А то некрасиво ж…

  6. Jman 10 июля 2008 at 20:53 Permalink

    2aratak, ну автор в самом начале поста написал что не претендует на своё авторство. А вот ссылка – правило хорошего тона. В принципе настоящий автор, не требовал ссылку при цитировании.

  7. kikaha 10 июля 2008 at 22:33 Permalink

    2aratak, ну автор в самом начале поста написал что не претендует на своё авторство.

    значит это не автор а копипастер

    В принципе настоящий автор, не требовал ссылку при цитировании.

    значит будем навариваться на деликатных нежадных авторах, которые вместо здрасьте сразу в лоб не требуют ссылку? я когда копипастю – мне пофигу – просил автор, или требовал – я поставлю ссылку на источник – для меня самого это важно в первую очередь.
    «Я помню чудное мгновение» – это очень красиво, но даже тому, кто никогда не читал Пушкина, я не буду тереть что это мои стихи – мне самому стыдно и неприятно будет, да, таким мама воспитала.

  8. Jman 10 июля 2008 at 23:03 Permalink

    Как сказал кто-то умный, если оно есть в интернет, значит у этого есть бесконечное количество копий.

  9. Я собственной персоной 12 июля 2008 at 14:18 Permalink

    Извините, у меня день рождения был, писал заметку на скорую руку, и честно говоря, забыл про ссылку ;-)

  10. Jman 12 июля 2008 at 21:15 Permalink

    Поздравляю :), как говорится с прошедшим.

  11. Sicon 13 июля 2008 at 0:25 Permalink

    поздравляемъ

  12. Sicon 13 июля 2008 at 0:33 Permalink

    [кстати, прикрути кнопку удаления сессии в комментировании]

  13. Dr.Death 16 июля 2008 at 18:39 Permalink

    кстати

    .win .ff3 {
    color: #000000;
    }

    не будет работать так как оба класа установлены у html а в css идет клас за класом селектор :)

  14. Евгений 18 июля 2008 at 5:10 Permalink

    Вот это то что давно искал спасибо.

  15. dip 22 июля 2008 at 11:48 Permalink

    Смысл от этого, тогда уж проще сделать отдельные файлы для каждого браузера, чтобы не грузить бестолковый для меня стиль IE / Safari / Oper’ы и еще кучки браузеров если я сижу в FF, да и вобще …

  16. FanToM 0T F_1M 22 августа 2008 at 15:02 Permalink

    Спасибо))Сохранил на винт))

  17. Вадим 17 сентября 2008 at 15:55 Permalink

    Неплохо продумано, но в основном все проблемы связаны с IE. Поэтому под все остальные браузеры можно не париться, потому что они обычно отображают так, как показывает опера или файерфокс. Для меня IE – это заноза в заднице, все там как-то криво.

  18. случайно зашел 16 октября 2008 at 17:05 Permalink

    ненавижу код без отступов ;-( уж в одну строку всё написали бы

  19. Alex 25 июня 2009 at 18:35 Permalink

    >Неплохо продумано, но в основном все проблемы связаны с IE. Поэтому под все остальные браузеры можно не париться
    Хе хе. А под другие ОС? Сравните ФФ 3 под мак и под вынь =)
    Полезный скрипт. Активно юзаю подобный.

  20. Toy 4 июля 2009 at 2:49 Permalink

    А если у меня к примеру. Как его совместить с win. ie.?

  21. manitu 18 октября 2009 at 21:36 Permalink

    Запарился разбираться с хаками для IE. Половина того что пишут миф.
    А за это большое человеческое спасибо.

  22. FOMICHJOVIl'ja29 1 июня 2011 at 17:48 Permalink

    тимбилдинг по отличной цене в Киеве

  23. Men's Supplements 25 февраля 2012 at 18:01 Permalink

    A few very nice things on this web site, I like that.

  24. Top Rated Testosterone Boosters 26 февраля 2012 at 21:55 Permalink

    great post, my partner and i definitely enjoy this amazing site, carry on it

  25. Randy Balwin 26 февраля 2012 at 23:48 Permalink

    I just want to tell you that I’m newbie to blogging and site-building and seriously loved this blog site. Likely I’m going to bookmark your blog . You certainly come with superb articles. With thanks for revealing your website page.

  26. Dong 29 февраля 2012 at 10:51 Permalink

    hope you never stop! This is one of the best blogs I have ever read. You have got some mad skill here, man. I just hope that you dont lose your style because youre definitely one of the coolest bloggers out there. Please keep it up because the internet needs someone like you spreading the word.

  27. Donaldson 29 февраля 2012 at 13:43 Permalink

    Do you mind if I quote a few of your posts as long as I provide credit and sources back to your webpage? My blog is in the exact same niche as yours and my visitors would genuinely benefit from a lot of the information you provide here. Please let me know if this ok with you. Thank you!

  28. Scrapebox forum 29 февраля 2012 at 15:15 Permalink

    A truly exciting examine, I could possibly not concur entirely, but you do make some actually legitimate points.

  29. disque dur ssd 29 февраля 2012 at 15:45 Permalink

    Very excellent visual appeal on this web site, I’d rate it 10.

  30. camescope hd 29 февраля 2012 at 16:26 Permalink

    I really like your writing style, good info , appreciate it for putting up : D.

  31. montre gps 29 февраля 2012 at 22:54 Permalink

    You are my inhalation, I own few web logs and rarely run out from post :). «Actions lie louder than words.» by Carolyn Wells.

  32. barbecue electrique 1 марта 2012 at 1:38 Permalink

    I like this post, enjoyed this one regards for putting up.

  33. white ceramic watches for women 1 марта 2012 at 2:38 Permalink

    Hey, you used to write great, but the last few posts have been kinda boring… I miss your super writings. Past few posts are just a little out of track! come on!»In politics stupidity is not a handicap.» by Napoleon Bonaparte.

  34. chaussure de foot 1 марта 2012 at 2:59 Permalink

    I loved up to you will receive performed right here. The cartoon is attractive, your authored subject matter stylish. nonetheless, you command get got an nervousness over that you would like be handing over the following. sick for sure come further in the past again as precisely the same nearly very continuously inside case you shield this increase.

  35. web design atlanta 1 марта 2012 at 4:38 Permalink

    You made some nice points there. I looked on the internet for the subject and found most people will go along with with your site.

  36. Ute 1 марта 2012 at 5:06 Permalink

    Wow, thanks for the sample sale tip – never knew something like that even existed…

  37. 10 yard dumpster marietta mn 1 марта 2012 at 6:20 Permalink

    Hi, where can I subscribe to your weblog? I like it, thanksCu

  38. Shemika Sjerven 1 марта 2012 at 8:58 Permalink

    It’s vital to get yourself a specialized decides your own buzzing in the ears before you begin healing the item. Most of the ear ringing can also be an indication of rather more serious difficulties. In addition, should the medical diagnosis is not tinnitus, then you will want in order to medicate or treat it inside of a unique way as compared to you would ringing in ears. Some people who definitely have ringing ears discover relief from their own affliction by utilizing appear treatment. You will find there’s easy research that you can concept when seem treatment method will allow you to cope with your own ringing ears. Track ones radio stations in between two gas stops. You’ll want to hear your static sound once you have tuned that concerning gas stops. When the interferance appear from your airwaves goggles your current ringing ears or perhaps will make it less noticeable (somewhat masks this), next appear treatment method will most likely support your lack of control.

  39. vps hosting 1 марта 2012 at 10:48 Permalink

    I just couldn’t depart your site prior to suggesting that I actually enjoyed the standard information a person provide for your visitors? Is gonna be back often to check up on new posts

  40. free proxy 2012 1 марта 2012 at 13:46 Permalink

    I like the valuable info you provide inside your articles. I’ll bookmark your weblog and check once more here regularly. I’m quite certain I’ll learn several new stuff proper here! Good luck for the next!

  41. machine a biere 1 марта 2012 at 15:12 Permalink

    Some really prize blog posts on this site, saved to bookmarks .

  42. compensation consulting firms 1 марта 2012 at 16:27 Permalink

    Needed to write you that very small remark to be able to thank you so much over again on your magnificent knowledge you’ve contributed at this time. It is certainly pretty open-handed of people like you to present unhampered all that a number of us would’ve distributed as an electronic book to make some dough for their own end, particularly considering the fact that you could possibly have done it in the event you wanted. Those concepts in addition acted like the good way to comprehend some people have similar passion really like my own to understand a whole lot more regarding this matter. I am sure there are a lot more pleasant sessions up front for individuals who browse through your blog post.

  43. velo enfant pas cher 1 марта 2012 at 17:15 Permalink

    Some truly excellent posts on this internet site, thanks for contribution. «Careful. We don’t want to learn from this.» by Bill Watterson.

  44. insurance claim tips 1 марта 2012 at 17:29 Permalink

    I was just searching for this information for a while. After 6 hours of continuous Googleing, finally I got it in your website. I wonder what is the lack of Google strategy that do not rank this type of informative websites in top of the list. Usually the top web sites are full of garbage.

  45. climatiseur mobile 1 марта 2012 at 18:52 Permalink

    Keep up the fantastic piece of work, I read few blog posts on this site and I conceive that your blog is real interesting and has got bands of fantastic info.

  46. trampoline avec filet 1 марта 2012 at 19:46 Permalink

    Really nice design and great articles , very little else we need : D.

  47. filmy+20 1 марта 2012 at 20:31 Permalink

    I don’t usually comment but I gotta tell thankyou for the post on this special one : D.

  48. montre hello kitty 1 марта 2012 at 21:17 Permalink

    We are a bunch of volunteers and opening a new scheme in our community. Your web site provided us with useful info to paintings on. You’ve done an impressive job and our entire group will likely be thankful to you.

  49. film cameras 1 марта 2012 at 22:26 Permalink

    I have discovered some new items from your web-site about personal computers. Another thing I have always considered is that laptop computers have become an item that each family must have for most reasons. They offer convenient ways in which to organize the home, pay bills, search for information, study, tune in to music and perhaps watch television shows. An innovative approach to complete all of these tasks is a laptop computer. These pc’s are mobile ones, small, highly effective and easily transportable.

  50. whiteceramicwatches.net 2 марта 2012 at 0:31 Permalink

    I like this site very much so much fantastic info . «She refused to be bored chiefly because she wasnt boring.» by Zelda Fitzgerald.


Оставить комментарий