[英]remove addEventListener for font-weight - Javascript
I created javascript eventListener by using javascript for my dropdown link.我通过使用 javascript 作为我的下拉链接创建了 javascript eventListener。 When I click on 'bold', everything turn bold.当我点击“粗体”时,一切都变成了粗体。 It is ok for me but I want to remove it when clicking.对我来说没问题,但我想在单击时将其删除。 When I click again, my removeListener does not work, it is missing something I guess.当我再次单击时,我的 removeListener 不起作用,我猜它缺少了一些东西。
Thank you in advance.先感谢您。
//HTML
<nav class="navBar">
<div class="dropdown">
<button class="dropbtn" id="dropbutton">Style menu</button>
<div class="dropdown-content">
<a href="#" class="bold">Bold</a>
<a href="#" class="italic">Italic</a>
</div>
</div>
<div class="dropdown">
<button class="dropbtn" id="dropbutton1">Thèmes site</button>
<div class="dropdown-content">
<a href="#" class="fonce">Fonce</a>
<a href="#" class="pale">Pale</a>
</div>
</div>
</nav>
// JAVASCRIPT
const bold = document.querySelector(".bold");
const italic = document.querySelector(".italic");
const fonce = document.querySelector(".fonce");
function Mystyle(){
bold.style.fontWeight = "bold";
italic.style.fontWeight = "bold";
fonce.style.fontWeight = "bold";
};
bold.addEventListener("click", Mystyle);
// It does not work
function removeEvent() {
bold.removeEventListener("click", Mystyle);
}
Do not remove the event listener;不要删除事件监听器; instead, change the styles (or toggle a class) depending on the current state for each click.相反,根据每次点击的当前 state 更改 styles(或切换类)。
function Mystyle(){
if (bold.style.fontWeight === 'bold')
bold.style.fontWeight = italic.style.fontWeight = fonce.style.fontWeight = "";
else
bold.style.fontWeight = italic.style.fontWeight = fonce.style.fontWeight = "bold";
};
bold.addEventListener("click", Mystyle);
It is more convenient to toggle a class instead:切换 class 更方便:
function Mystyle() { document.querySelector('.navBar').classList.toggle('bold'); } document.querySelector('.bold').addEventListener("click", Mystyle);
.navBar.bold.bold, .navBar.bold.italic, .navBar.bold.fonce { /* or perhaps use.navBar.bold a */ font-weight: bold; }
<nav class="navBar"> <div class="dropdown"> <button class="dropbtn" id="dropbutton">Style menu</button> <div class="dropdown-content"> <a href="#" class="bold">Bold</a> <a href="#" class="italic">Italic</a> </div> </div> <div class="dropdown"> <button class="dropbtn" id="dropbutton1">Thèmes site</button> <div class="dropdown-content"> <a href="#" class="fonce">Fonce</a> <a href="#" class="pale">Pale</a> </div> </div> </nav>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.