简体   繁体   English

使用Jquery切换HTML和CSS

[英]Using Jquery to toggle HTML and CSS

I'm looking to use jquery for a sort of toggle button to toggle between the two below states; 我正在寻找使用jquery的一种切换按钮来在以下两个状态之间进行切换;

切换A

切换B

So everything in picture A (above the red line) is hidden when i click the Toggle Button/link and when i click the toggle button again, it reappears. 因此,当我单击“切换按钮” /链接时,图片A中的所有内容(红线上方)都被隐藏,当我再次单击切换按钮时,它会重新出现。

I've been looking into Jquerys toggleClass function; 我一直在研究Jquerys toggleClass函数;

$("button").click(function(){
$("p").toggleClass("main");
});

But this i beleive would only hide the CSS, not the HTML too. 但是我相信这只会隐藏CSS,而不会隐藏HTML。 Am i misusing the function or is not make for this? 我在滥用功能吗?

thanks 谢谢

Here is a working example: 这是一个工作示例:

http://jsfiddle.net/pV7Qe/ http://jsfiddle.net/pV7Qe/

<div class="header">header</div>
<div class="menu">
    <div class="my-toggle">toggle</div>
</div>
<div class="content">
content            
</div>

.header
{
    background:lime;
}
.menu
{
    height:100px;
    background:gray;        
}
.my-toggle
{
    width:100px;
    background:red;
    cursor:pointer;
}
.content
{
    height:500px;            
    background:#ddd;
}​

$(".my-toggle").click(function() {
  $(".header").slideToggle();
});

如果您可以将红线上方的所有内容放入具有唯一ID的单个包含元素中,则只需在单个元素上使用.toggle() jQuery函数即可实现所需的功能。

Consider two classes 考虑两类

.hide{visibility: hidden;}
.show{visibility: visible;}

Now use this JQuery Code 现在使用此JQuery代码

$("button").click(function(){
$("p").toggleClass('hide','show');
});

This would solve your problem. 这样可以解决您的问题。

Try using the toggle function. 尝试使用切换功能。

$("idOfButton").click(function(){
    $(".main").toggle();
});

Use the toggle function without any parameter.. 使用不带任何参数的切换功能。

   $("button").click(function(){
$("p").toggleClass();
});

This should work. 这应该工作。

You can use slideToggle() , toggle() or toggleClass('hidden') 您可以使用slideToggle()toggle()toggleClass('hidden')

.hidden {
    display: none;
}

References: 参考文献:

No reason to use toggleClass and have extra css for a hidden class. 没有理由使用toggleClass并为隐藏类提供额外的CSS。

Simply use toggle, or slideToggle for a better effect, which everyone here has suggested. 只需使用切换或slideToggle即可获得更好的效果,这在这里每个人都建议。

My only added input would be is that instead of 我唯一添加的输入是

$('.buttons').click(function(){
    $('#div').slideToggle();
});

I believe it is better practice to use 'on' 我认为使用“ on”是更好的做法

$('.buttons').on('click', function(){
    $('#div').slideToggle();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM