LoginSignup
0
0

More than 5 years have passed since last update.

【Javascript】プレーンな感じでcssを追加する

Posted at

なにができるのか

css指定を、
{backgroundColor:"red"}
な感じでなく
"background-color:red;"
な感じで動的に設定できます。

いる?

  • JSON形式だとダブルクォーテーションとかCamel型とか面倒
  • ターゲットが居なくてもスタイル指定できる。 datepickerなど呼び出したときにだけ生まれる要素に対してスタイルを付与する場合、 ファイルでやると動的に変更できないし、無関係の契機でスタイルを変更したくてもその瞬間にはターゲットの要素が存在しない・・・ みたいなときに役立ちます。

仕組み

styleタグを作ってその中にcssをぺたり
名前をつければ書き換えもできます。

ソースコード

jquery.plaincss.js
;(function($, undefined){
  $.fn.extend({
    plaincss:function(o){

      if (typeof o !== 'object') {
        var _plaincss = o;
        o = {};
        o.plaincss = _plaincss;
      }

      o = o || {};
      var needs = {name:"", plaincss: undefined};

      $.extend(needs, o);

      var doc = "";

      if (typeof o.plaincss === 'function') {
        doc = o.plaincss.toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];
      } else if(typeof o.plaincss === 'string') {
        doc = o.plaincss;
      }

      var name = o.name || "__ncss" +(new Date()).getTime();

      this.find("#"+name).remove();
      if (doc) {
        this.append($("<style />").attr("id", name).html(doc));
      }
    }
  });
})(jQuery);

使い方

// あんまり意味ない書き方
$("head").plaincss("div{background:red;}");

// 通常の使い方
var _css = "\
div.red {\
background-color:red;\
}\
div.blue {\
background-color:blue;\
}\
";
$("head").plaincss({name:"hogehoge",plaincss:_css});

// ヒアドキュメント風も対応
$("head").plaincss({
  name:"hogehoge",
  plaincss:function(){/*
    div.red{
      background-color:red;
    }
    div.blue{
      background-color:blue;
    }
  */}
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0