如何在jquery中循环此函数?

时间:2015-03-23 18:32:36

标签: javascript jquery html loops

    $( "#transbox1" ).one( "mouseenter", function() {
  $( this ).css( "width", "+=200" );
  $( this ).css( "height", "+=200" );
});
$( "#transbox1" ).one( "mouseleave", function() {
  $( this ).css( "width", "-=200" );
  $( this ).css( "height", "-=200" );
});
$( "#transbox2" ).one( "mouseenter", function() {
  $( this ).css( "width", "+=200" );
  $( this ).css( "height", "+=200" );
});
$( "#transbox2" ).one( "mouseleave", function() {
  $( this ).css( "width", "-=200" );
  $( this ).css( "height", "-=200" );
});
$( "#transbox3" ).one( "mouseenter", function() {
  $( this ).css( "width", "+=200" );
  $( this ).css( "height", "+=200" );
});
$( "#transbox3" ).one( "mouseleave", function() {
  $( this ).css( "width", "-=200" );
  $( this ).css( "height", "-=200" );
});
$( "#transbox4" ).one( "mouseenter", function() {
  $( this ).css( "width", "+=200" );
  $( this ).css( "height", "+=200" );
});
$( "#transbox4" ).one( "mouseleave", function() {
  $( this ).css( "width", "-=200" );
  $( this ).css( "height", "-=200" );
});

我有4个盒子,使用mouseenter,盒子将增长200px,当鼠标离开盒子时,盒子将变小200px。我一直这样做多么好吃?

4 个答案:

答案 0 :(得分:3)

只需为所有人​​添加一个课程

   <div class="myClass" id="transbox1"></div>

   $( ".myClass" ).on( "mouseenter", function() {
    $( this ).css( "width", "+=200" );
    $( this ).css( "height", "+=200" );
   });
  $( ".myClass" ).on( "mouseleave", function() {
    $( this ).css( "width", "-=200" );
    $( this ).css( "height", "-=200" );
  });

答案 1 :(得分:2)

将一个类应用于所有元素,然后您可以使用类选择器同时处理所有元素:

HTML:

<div id"transbox1" class="transbox"></div>
<div id"transbox2" class="transbox"></div>
<div id"transbox3" class="transbox"></div>
...

使用Javascript:

$( ".transbox" ).on( "mouseenter", function() {
  $( this ).css( "width", "+=200" );
  $( this ).css( "height", "+=200" );
});
$( ".transbox" ).on( "mouseleave", function() {
  $( this ).css( "width", "-=200" );
  $( this ).css( "height", "-=200" );
});

答案 2 :(得分:1)

请尝试使用以下代码段。

$("div[id^='transbox']").one( "mouseenter", function() {
  $( this ).css( "width", "+=200" );
  $( this ).css( "height", "+=200" );
});
$("div[id^='transbox']").one( "mouseleave", function() {
   $( this ).css( "width", "-=200" );
   $( this ).css( "height", "-=200" );
});

我假设你的盒子是div标签。

答案 3 :(得分:0)

为所有这些框提供通用名称或类,然后使用下面的代码,因为它们具有通用名称 - transbox

$("[name=transbox]" ).one( "mouseenter", function() {
  $( this ).css( "width", "+=200" );
  $( this ).css( "height", "+=200" );
});
$("[name=transbox]" ).one( "mouseleave", function() {
  $( this ).css( "width", "-=200" );
  $( this ).css( "height", "-=200" );
});