繁体   English   中英

切换按钮文本和段落背景

[英]Toggle button text and paragraph background

老师让我们做一个JS作业。

JavaScript

window.onload = function() {
  var button = document.getElementsByTagName("button");
  button[0].onclick = changeBackground;
}

function changeBackground() {
  var allParas = document.getElementsByTagName("p");
  for (var i = 0; i < allParas.length; i++) {
    allParas[i].style.backgroundColor = "yellow";
  }
}

以下是任务详情:

修改 HTML 代码以添加到按钮中。 编写相应的 JS 代码(以不显眼的方式)将按钮链接到一个在单击时突出显示段落的函数。 该按钮应充当“切换”,即,如果段落已经突出显示,则单击按钮取消突出显示它们。 如果段落没有突出显示,则单击按钮突出显示它们。 按钮的文本应该改变以反映这一点(见下文)。 您可以引入额外的变量来完成这项工作。

只需编写另一个使 CSS 无效的函数并将其链接到另一个按钮。

function unchangeBackground(){
for (var i = 0; i < allParas.length; i++) {
   allParas[i].style.backgroundColor = " ";
} }

你的意思是:

 <!DOCTYPE html> <html> <head> <meta name="author" content="K."> <title>Someone's assignment</title> <style> .yellow { background-color: yellow; } </style> </head> <body> <button id="toggle" type="button">Toggle highlighting</button> <!-- If you don't give it type="button", it works as a submit button. --> <p> Ni hao, Wo jiao K.. </p> <p> And this is another paragraph. </p> <script> const toggle_button = document.getElementById("toggle"); toggle_button.addEventListener("click", _ => { if(toggle_button.getAttribute("data-state") === "on") { toggle_button.setAttribute("data-state", "off"); } else { toggle_button.setAttribute("data-state", "on"); } const on = toggle_button.getAttribute("data-state") === "on"; Array.from(document.querySelectorAll("p")).forEach(p => { if(on) { p.classList.add("yellow"); } else { p.classList.remove("yellow"); } }); }); </script> </body> </html>

使用classList.toggle

 document.getElementById("button").addEventListener("click", function() { [].forEach.call(document.querySelectorAll("p"), p => { p.classList.toggle("highlight"); }); this.innerHTML = (this.innerHTML === "Highlight") ? "Unhighlight" : "Highlight"; })
 .highlight { background: yellow; }
 <p> Cultivar brewed, coffee, spoon breve lungo spoon robust black. Barista percolator doppio, cup mug, crema, crema acerbic wings mug pumpkin spice. Lungo, aromatic, iced et, cup americano galão coffee to go. </p> <p> Cultivar brewed, coffee, spoon breve lungo spoon robust black. Barista percolator doppio, cup mug, crema, crema acerbic wings mug pumpkin spice. Lungo, aromatic, iced et, cup americano galão coffee to go. </p> <button id="button">Highlight</button>

暂无
暂无

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

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