1

ある DIV から別の DIV にいくつかの CSS スタイルをコピーしたいと考えています。

  1. 「ONE」DIVをクリックします

  2. 次に、jQuery が ARRAY から CSS プロパティのリストを読み取ります

  3. 次に、これらのプロパティを DIV "ONE" から DIV "TWO" にコピーします。

これは私の試みですが、うまくいきません。どうしたの?

「JsFiddle の例」 .

HTML

 <div class="one">Click HERE on this DIV, to TRANSFER CSS properties From this ONE</div>
 <div class="two">To this TWO</div>

CSS

* {
   background-color:gray;
}
.one {
   color: red;
   font-size:12px;
   width: 100px;
   height: 100px;
   background-color: white;
   margin: 20px;
   padding: 20px;
   font-weight: bold;
}
.two {
   font-size:20px;
   color: blue;
   width: 200px;
   height: 200px;
   background-color: yellow;
   margin: 20px;
   padding: 20px;
}

jQuery

 $(document).ready(function(){
     $("div.one").click(function(){
         var $array = ['color','width','height', 'background-color', 'font-weight', 'font-size'];
         $(this).each( $array , function(item, value){
             $("div.two").css(value, $(this).css(value));
         });
     });
 });
4

1 に答える 1

4
  1. jQueryJSFiddle の左側のパネルで選択します。
  2. $.each(array, fn)の代わりに使用し$().each(array, fn)ます。
  3. $(this)などの変数に格納します$this = $(this)。ループ内では、クリックされた DOM 要素ではなくthis、配列要素を参照します。
  4. (重要ではない) jQuery 以外のオブジェクトの前に. を付けないでください$

デモ: http://jsfiddle.net/meU9M/2/

$(document).ready(function(){
    $("div.one").click(function(){
        var array = ['color','width','height', 'background-color', 'font-weight', 'font-size'];
        var $this = $(this);
        $.each( array , function(item, value) {
            $("div.two").css(value, $this.css(value));
        });
    });
});
于 2012-04-15T09:44:07.380 に答える