2

自分自身にjqueryを教えようとしています。次のコードスニペットは正常に機能しますが、コードをより短く/より効率的にすることは可能だと思います。

  //Alter the stylesheet to hide the contents of the page initially. 
  //When the page is loaded, fade in the contents slowly.
  var backgroundBuffer;
  $('p').mouseover(function() {
      backgroundBuffer = $(this).css("background-color");
      $(this).css({"background-color": 'yellow'});
    }).mouseout(function(){
      $(this).css({"background-color": backgroundBuffer});
  });

「backgroundBuffer」をグローバルに宣言したくないのは、二度と使用しないからです。しかし、.mouseover()内で宣言すると、システムは後の.mouseout()でそれを認識しません。

  //Alter the stylesheet to hide the contents of the page initially. 
  //When the page is loaded, fade in the contents slowly.
  $('p').mouseover(function() {
      var backgroundBuffer; 
      backgroundBuffer = $(this).css("background-color");
      $(this).css({"background-color": 'yellow'});
    }).mouseout(function(){
      $(this).css({"background-color": backgroundBuffer});
  });

あなたの助けのためのthx!

4

2 に答える 2

3

jQueryデータを使用して初期値を保存します...

$('p').mouseover(function() {
  $(this).data('oldcolor', $(this).css("background-color")).css('background-color', 'yellow');
}).mouseout(function(){
  $(this).css("background-color",$(this).data('oldcolor'));
});
于 2013-01-14T16:47:21.337 に答える
2

これは、jQuery データ メソッドが役立つ状況です。そうすれば、jQuery オブジェクトからその変数にアクセスできます。

 //Alter the stylesheet to hide the contents of the page initially. 
  //When the page is loaded, fade in the contents slowly.
  $('p').mouseover(function() {
      var $this = $(this);
      $this.data('backgroundbuffer', $this.css("background-color")).css({"background-color": 'yellow'});
    }).mouseout(function(){
      var $this = $(this);
      $this.css({"background-color": $this.data('backgroundbuffer')});
  });
于 2013-01-14T16:48:22.550 に答える