【问题标题】:How to Slide an Element Horizontally如何水平滑动元素
【发布时间】:2018-03-18 22:53:47
【问题描述】:

我需要在 click 函数中添加 else 语句,以便在第二次单击按钮时 .container 消失。

function() {

    $('div.container').css({'width':'350px'});

    } else {

    $('div.container').css({'width':'0'});

     }

});

编辑:

我需要元素在单击按钮时向左切换。

【问题讨论】:

  • if()在哪里?
  • 不确定在哪里添加 if
  • 使用 toggleClass() 和 css 来做到这一点。如果单击相同按钮两次以上会发生什么?
  • 我想用 .animate({ width: 'toggle'},

标签: javascript jquery css css-animations


【解决方案1】:

toggle() 方法:

使用 jQuery 你可以使用toggle() 方法。

toggle() 方法在选中元素的 hide() 和 show() 之间切换。

所以你可以简单地拥有

$('#buttonId').on('click', function(){
    $('#container').toggle();
})
div{
  background-color: #a8a8ff;
  height: 100px;
  width: 350px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonId">Click Me!</button>
<div id="container" class="long"></div>

toggleClass() 方法:

根据您的评论,如果您想切换样式(例如:宽度),最好为您的样式定义一个类并使用toggleClass() 方法。

toggleClass() 方法在添加和删除类之间切换。

$('#buttonId').on('click', function(){
    $('#container').toggleClass('long short');
})
div{
  background-color: #a8a8ff;
  height: 100px;
}

.long{
  width: 350px;
}

.short{
  width: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonId">Click Me!</button>
<div id="container" class="long"></short>

animate() 方法:

根据您的第二个建议,您可以使用animate() 方法来模拟幻灯片功能。

jQuery animate() 方法可让您创建自定义动画。

要将元素向左滑动:(感谢JQGeek 他的回答here。)

$('#buttonId').on('click', function(){
    $('#container').animate({width:'toggle'},350);
})
div{
  background-color: #a8a8ff;
  height: 100px;
  width: 350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonId">Click Me!</button>
<div id="container"></div>

【讨论】:

  • 是的,我如何切换容器的宽度 $('div.container').css({'width':'350px'});
  • 是的,谢谢,但我希望它从左侧滑动切换。我可以使用它还是需要使用 .animate?
  • @Dev 我再次更新了我的答案。检查一下滑动切换功能。
  • 如果我将内容添加到容器中,我如何将其也滑掉?
  • @Dev 这实际上不是幻灯片,它更像是一种类似幻灯片的效果,但我们正在切换width 属性。如果你想要一张实际的幻灯片(在视图内外移动元素),我建议你看看this question 和前两个答案。
【解决方案2】:

你可以这样做

$(document).on('click', 'button_selector', function () {
    if (true) {
        // your code
    }
    else{
        // your code
    }
});

建议

您可以为此使用切换

$(document).on('click', 'button_selector', function () {
    $('div.container').toggle();
});

【讨论】:

  • 为什么我需要'button_selector'
  • 处理事件的按钮,你必须提供像id, class这样的按钮选择器或任何其他选择器属性
  • 我唯一的问题是它不会横向切换
  • toggle 将切换您的 div 或说出元素,这意味着它将显示或消失您的元素,例如显示或隐藏
  • 我想要从左侧滑动切换 我可以使用这个还是需要使用 .animate?
【解决方案3】:

你可以关注我的代码

$(function(){
   var firstClick = 0;
   $("button").click(function(){
       firstClick++;
       if(firstClick==2)
          $('div.container').hide();
       else
         $('div.container').show();
   });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 2021-03-23
    相关资源
    最近更新 更多