[英]Using jquery to toggle a CSS property and also animate it
I have the below code: 我有以下代码:
$('#button').click(function () {
$('#divName').animate({
top: 90%,
}, 1000, function(){
});
});
When the button is clicked, it sets the top property for the DIV to 90%. 单击该按钮时,它将DIV的top属性设置为90%。
When I click the button again, I went to revert the CSS back to its original (50%). 当我再次单击该按钮时,我将CSS恢复为原始状态(50%)。
How can I do this? 我怎样才能做到这一点?
My attempt which seems to work but seems messy: 我的尝试似乎可行,但看起来很混乱:
var state = false;
$('#button').click(function () {
if (state) {
state = false;
$('#divName').animate({
top: '50%',
}, 1000, function(){
});
} else if (state == false){
state = false;
$('#divName').animate({
top: '90%',
}, 1000, function(){
});
}
});
You could do it with CSS transitions . 您可以使用CSS过渡来做到这一点。 With jQuery just toggle a class. 使用jQuery只需切换一个类。
$('#button').click(function () { $('#divName').toggleClass('animate'); });
.container { position: relative; height: 80vh; border: 2px solid red; } #divName { position: absolute; top: 50%; width: 100%; height: 50px; border: 2px solid blue; transition: top 1s linear; } .animate { top: 90% !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="button">Press</button> <div class="container"> <div id="divName"></div> </div>
You could improve this with some minor changes: 您可以通过一些小的更改来改进此功能:
var state = false; $('#button').click(function() { percent = state ? 50 : 90 $('#divName').animate({ top: percent + '%', }, 1000, function() {}); state = !state; });
div { background-color: green; position: absolute; top: 50%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p id="button">clickme</p> <div id="divName"> <p>hello</p> </div>
here is one way to do it by removing the style added by jQuery 这是删除jQuery添加的样式的一种方法
var div = $('#divName'); $('#button').click(function () { var style = div.attr("style"); if(style && style.includes("top")){ div.attr("style", style.replace(/top:[^;]+;/,"")); }else{ div.css("top", "90%"); } });
#divName{ width: 20px; height: 20px; border: black solid 1px; position: absolute; top:50%; /*you need to give an init value to top*/ transition: top 1s linear; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> <button id="button">click me</button> <div id="divName"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.