Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 根据div是否具有特定类设置动画到特定高度_Jquery_If Statement - Fatal编程技术网

Jquery 根据div是否具有特定类设置动画到特定高度

Jquery 根据div是否具有特定类设置动画到特定高度,jquery,if-statement,Jquery,If Statement,我有一个div,我想根据单击元素设置3种不同高度的动画。我想用类来做,所以如果单击其中一个被单击的元素,一个名为d_foxboro的div,它有一个高度类,位置滑块被设置为第一个高度,如果单击另一个div,d_main,它有一个高度类,那么位置滑块被设置为第二个高度,依此类推 $( "#d_Foxboro" ).click(function(){ $( "#location_slider" ).animate({ "height": 500 }, 450 ); }); 我个人喜欢使用.on()

我有一个div,我想根据单击元素设置3种不同高度的动画。我想用类来做,所以如果单击其中一个被单击的元素,一个名为d_foxboro的div,它有一个高度类,位置滑块被设置为第一个高度,如果单击另一个div,d_main,它有一个高度类,那么位置滑块被设置为第二个高度,依此类推

$( "#d_Foxboro" ).click(function(){
$( "#location_slider" ).animate({
"height": 500
}, 450 );
});

我个人喜欢使用
.on()
方法绑定事件,因为如果元素被动态添加到DOM中,它允许我轻松地更改它

$( "#d_Foxboro" ).on("click", function(){
    var height = 0;
    if ($(this).hasClass() == "someClass"){
        height = 100;
    }
    else
    {
        height = 200;           
     }
    $( "#location_slider" ).animate({
         "height": height
       }, 450 );
});

基本上,使用hasClass查看元素所属的类,然后根据类设置包含高度的变量,具体取决于单击时的类检查类,然后根据该类设置高度变量

$( "#d_Foxboro" ).click(function(){
  // Default height
  var h = 0; // Set to a default number
  // Class of clicked item
  var h_class = $(this).attr('class');

  // Check class and set height based of which class
  if(h_class == "something") {
    h = 500;
  } else if(h_class == "something else") {
    h = 400
  }

  $( "#location_slider" ).animate({
    "height": h
  }, 450 );

});

您正在使用ID作为选择器来添加click事件处理程序,因此您的语句“取决于单击的元素是否具有特定类”对我来说没有意义,因为页面上每个元素的ID都必须是唯一的。你能澄清你的问题吗?!如何添加第三类选项?只需添加另一个选项,如果您已经相应地编辑了我的代码,那么您现在需要做的就是使用您自己的类更改“class1”、“class2”和“class3”,并使用您自己的值更改高度。作为一个元素,如果答案不正确,则可以获得多个类。正确答案是使用hasClass()或if($(this).attr('class').indexOf(“something”)!=-1)
$( "#d_Foxboro" ).click(function(){
  // Default height
  var h = 0; // Set to a default number
  // Class of clicked item
  var h_class = $(this).attr('class');

  // Check class and set height based of which class
  if(h_class == "something") {
    h = 500;
  } else if(h_class == "something else") {
    h = 400
  }

  $( "#location_slider" ).animate({
    "height": h
  }, 450 );

});