[英]how to toggle css via jquery with the .css function
the function is triggered via a button so I thought every time you push it will check x set the background accordingly and put x in the other state so the next push gives the other result 该功能是通过按钮触发的,因此我认为每次按下该按钮都会检查x相应地设置背景,并将x置于另一种状态,以便下次按下时可以得出其他结果
I just saw that I can use the .css in an .toggle but I'm still curious why my solution wont work 我刚刚看到可以在.toggle中使用.css,但是我仍然很好奇为什么我的解决方案无法正常工作
var x = 0;
function toggledark(x){
if (x == 0) {
$('body').css({'background-color': 'red'});
x+=1;
return x;
}
else {
$('body').css({'background-color': 'black'});
x-=1;
return x;
}
}
I thought it will toggle but I only get black and it stays this way 我以为它会切换,但我只会变黑并且保持这种状态
no need for x
as integer unless you have another actions to do .. But while you using red
and black
you can use it like this 不需要x
作为整数,除非您有其他操作要执行..但是当您使用red
和black
,可以像这样使用它
var color = 'red'; // default background color function toggledark(){ color = (color == 'red') ? 'black' : 'red'; $('body').css({'background-color': color }); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="toggledark()">Toggle</button>
AND if you have another actions to do and you must use if statement for it you can use it like AND,如果您还有其他操作要做,并且必须使用if语句,则可以像
var color = 'red'; // default background color function toggledark(){ color = (color == 'red') ? 'black' : 'red'; $('body').css({'background-color': color }); if(color == 'red'){ console.log('Red Theme'); } if(color == 'black'){ console.log('Black Theme'); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="toggledark()">Toggle</button>
NOTE: I don't think this is a good solution, I would do it with classes, but I'll provide the code for your question if you want to do it this way 注意:我认为这不是一个很好的解决方案,我会使用类来解决,但是如果您想这样做,我将为您的问题提供代码
Here is the working code: http://jsfiddle.net/8ygrebp2/3/ 这是工作代码: http : //jsfiddle.net/8ygrebp2/3/
I would do it like that since you are using Jquery: 我会那样做,因为您正在使用Jquery:
HTML: HTML:
<button class="toggle">
Click me
</button>
JQuery: JQuery的:
var x = 0;
$('body').on('click', '.toggle', function(){
if(x == 0){
$('body').css('background-color', 'black');
x+=1;
} else {
$('body').css('background-color', 'red');
x-=1;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.