切换按钮文本和段落背景

时间:2017-11-12 00:14:53

标签: javascript html

老师要我们做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代码(以不引人注目的方式)将按钮链接到一个函数,该函数在单击时突出显示段落。按钮应该充当“切换”,也就是说,如果段落已经突出显示,则单击该按钮不会突出显示它们。如果段落未突出显示,则单击按钮会突出显示它们。按钮的文本应该更改以反映这一点(见下文)。您可以引入其他变量来实现此功能。

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

你的意思是:

<!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>

答案 2 :(得分:0)

使用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>
SASS
  1. tools (put bourbon or bitters here)
  2. basics (body, links or common things)
  3. modules (reuasable stuff. Boxes, cards, etc)
  4. layouts (your containers, footers, headers etc)