我需要向点击函数添加 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/