我需要向点击函数添加一个else语句,以便.container在第二次单击按钮时消失。如何水平滑动元素
function() {
$('div.container').css({'width':'350px'});
} else {
$('div.container').css({'width':'0'});
}
});
编辑:
我需要切换向左滑动按钮上点击的元素。
我需要向点击函数添加一个else语句,以便.container在第二次单击按钮时消失。如何水平滑动元素
function() {
$('div.container').css({'width':'350px'});
} else {
$('div.container').css({'width':'0'});
}
});
编辑:
我需要切换向左滑动按钮上点击的元素。
切换()方法:
使用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()方法来模拟幻灯片功能。
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>
你可以按照我的代码
$(function(){
var firstClick = 0;
$("button").click(function(){
firstClick++;
if(firstClick==2)
$('div.container').hide();
else
$('div.container').show();
});
})
你可以这样做
$(document).on('click', 'button_selector', function() {
if (true) {
// your code
}
else{
// your code
}
});
建议
您可以使用切换这个
$(document).on('click', 'button_selector', function() {
$('div.container').toggle();
});
'if()'在哪里? –
不知道在哪里添加如果 – Dev
使用toggleClass()与CSS来做到这一点。如果点击两次以上相同的按钮,会发生什么? –