javascript - 如何水平滑动元素

标签 javascript jquery css css-animations

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

function() {

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

    } else {

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

     }

});

编辑:

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

最佳答案

toggle() 方法:

使用 jQuery,您可以使用 toggle()方法。

The toggle() method toggles between hide() and show() for the selected elements.

所以你可以简单地拥有

$('#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() 会更好、更清晰。方法。

The toggleClass() method toggles between adding and removing the class.

$('#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()模拟幻灯片功能的方法。

The jQuery animate() method lets you create custom animations.

将元素向左滑动:(感谢 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>

关于javascript - 如何水平滑动元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46617494/

相关文章:

html - CSS 以不同颜色为类型的第 n 个子元素着色

javascript - 通过 Javascript 在两个其他字符串之间查找字符串的有效方法

javascript - Canvas 创建两个独立的动画瀑布对象

javascript - 将数组项的顺序列表设置为零的最快方法

javascript - jQuery 圆形菜单导航在切换关闭后创建小圆圈

javascript - Stripe with Rails 捐款

iphone - 在 iPad/iPhone 上使用 CSS @font-face

javascript - 为什么 while 循环不起作用?

javascript - 淡入、淡出标签,然后在重复该过程之前更改文本

javascript - 可以在服务器上看到自定义字体,但不能在本地看到