[英]Make content of header disappear when menu opens
I basically want to make that when I press on a button the first time it adds display: none;我基本上想在我第一次按下按钮时添加 display: none; to an element and when I press it again it makes the element appear again (so add display: none;).
到一个元素,当我再次按下它时,它会再次出现该元素(因此添加 display: none;)。 How would I do this with jQuery?
我将如何用 jQuery 做到这一点?
This is the jQuery I tried to implement but as I'm new to Javascript I don't know why it isn't working.这是我尝试实现的 jQuery,但由于我是 Javascript 新手,我不知道为什么它不起作用。
$('#menuBtn').click(function() {
var clicks = $(this).data('clicks');
if (clicks) {
$('.header-text').css({
'display': 'none'
});
} else {
$('.header-text').css({
'display': 'block'
});
}
$(this).data("clicks", !clicks);
});
Use toggle or slideToggle (With animation)使用切换或滑动切换(带动画)
$('#menuBtn').on('click', function() { $('.header-text').toggle(); }); $('#menuBtnSlide').on('click', function() { $('.header-text').slideToggle(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="menuBtn">Toggle</button> <button id="menuBtnSlide">SlideToggle</button> <div class="header-text"> This content must me show and hide </div>
You could supply a modifier class in some external stylesheet for hiding the text and toggle it via toggleClass .您可以在某些外部样式表中提供修饰符类来隐藏文本并通过toggleClass切换它。
Word of advice: It's best not to use something like toggle because it will inject inline css into your elements, making it difficult to override in the long-run for something so simplistic.忠告:最好不要使用诸如切换之类的东西,因为它会将内联 css 注入您的元素,从长远来看,很难覆盖如此简单的东西。
const $headerText = $('.header-text'); $('#menuBtn').click(function() { $headerText.toggleClass('header-text--hidden'); });
.header-text--hidden { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="menuBtn" type="button">Toggle</button> <header> <p class="header-text">Text 1</p> <p class="header-text">Text 2</p> <p class="header-text">Text 3</p> <p class="header-text">Text 4</p> </header>
You actually don't need jQuery for this.您实际上不需要为此使用 jQuery。
You can add CSS rule to set .hidden
to display: none
and then toggle that class when the button is clicked.您可以添加 CSS 规则以将
.hidden
设置为display: none
然后在单击按钮时切换该类。
To catch the click event on the button, you need a click event listener要捕获按钮上的单击事件,您需要一个单击事件侦听器
const header = document.querySelector('.header'); const toggle = document.querySelector('.menu-toggle'); toggle.addEventListener('click', () => { header.classList.toggle('hidden') });
.header { background: red; height: 3em; } .hidden { display: none; }
<header class="header"></header> <button class="menu-toggle">Click me!</button>
.hidden{display:none !important;}
$('#menuBtn').click(function() {
$('.header-text').toggleClass("hidden");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.