如何更改HTML文档上Javascript元素的文本颜色

时间:2018-12-22 01:25:00

标签: javascript

我用html中的类故事创建了一个段落元素,以供我的JavaScript填充。如何更改itemX,itemY,itemZ的文本颜色,以便一旦按下按钮,它们就可以从storyText字符串的其余部分中脱颖而出?

由于在按下JS按钮之后直到在html文档中才创建newStory字符串,所以我对如何定位itemXYZ变量感到困惑。

//1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS

var customName = document.getElementById('customname');
var randomize = document.querySelector('.randomize');
var story = document.querySelector('.story');

function randomValueFromArray(array) {
  return array[Math.floor(Math.random() * array.length)];
}

//2. TEXT STRINGS
let insertX = ['Willy the Goblin', 'Big Daddy', 'Father Christmas'];
let insertY = ['the soup kitchen', 'Disneyland', 'the White House'];
let insertZ = ['spontaneously combusted', 'melted into a puddle on the sidewalk', 'turned into a slug and crawled away'];

//3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION

randomize.addEventListener('click', result);

function result() {


  let itemX = randomValueFromArray(insertX);
  let itemY = randomValueFromArray(insertY);
  let itemZ = randomValueFromArray(insertZ);

  //replaces inserts in stortText w/ randomized strings from itemX,Y,Z
  let newStory = `It was 94 fahrenheit outside, so ${itemX} went for a walk. When they got to ${itemY}, they stared in horror for a few moments, then ${itemZ}. Bob saw the whole thing, but was not surprised — ${itemX} weighs 300 pounds, and it was a hot day.`;

  //replaces 'Bob' w/ custom name if given
  if (customName.value !== '') {
    let name = customName.value;
    newStory = newStory.replace('Bob', name);
  }

  //converts fahrenheit to centigrade & pounds to stone
  if (document.getElementById("uk").checked) {
    let temperature = Math.round((94 - 32) * 5 / 9) + ' centigrade';
    let weight = Math.round(300 * 0.071429) + ' stone';
    newStory = newStory.replace('94 fahrenheit', temperature);
    newStory = newStory.replace('300 pounds', weight);
  }

  story.textContent = newStory;
  story.style.visibility = 'visible';
}
body {
  font-family: helvetica, sans-serif;
  width: 350px;
}

label {
  font-weight: bold;
}

div {
  padding-bottom: 20px;
}

input[type="text"] {
  padding: 5px;
  width: 150px;
}

p {
  background: #FFC125;
  color: #5E2612;
  padding: 10px;
  visibility: hidden;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width">
  <link rel="stylesheet" type="text/css" href="generatorStyles.css">

  <title>Silly story generator</title>

</head>

<body>
  <div>
    <label for="customname">Enter custom name:</label>
    <input id="customname" type="text" placeholder="">
  </div>
  <div>
    <label for="us">US</label><input id="us" type="radio" name="ukus" value="us" checked>
    <label for="uk">UK</label><input id="uk" type="radio" name="ukus" value="uk">
  </div>
  <div>
    <button class="randomize">Generate random story</button>
  </div>
  <!-- Thanks a lot to Willy Aguirre for his help with the code for this assessment -->
  <p class="story"></p>

  <script src="main.js"></script>
</body>

</html>

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

您可以如下将itemX, itemY and itemZspan包裹起来

<span class="itemY">${itemY}</span>
<span class="itemX">${itemX}</span>
<span class="itemZ">${itemZ}</span>

然后,您可以使用上述HTML字符串设置 innerHTML story属性。现在,您可以通过它们各自的类名选择这些span,并相应地设置其样式。

演示:

//1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS

var customName = document.getElementById("customname");
var randomize = document.querySelector(".randomize");
var story = document.querySelector(".story");

function randomValueFromArray(array) {
  return array[Math.floor(Math.random() * array.length)];
}

//2. TEXT STRINGS
let insertX = ["Willy the Goblin", "Big Daddy", "Father Christmas"];
let insertY = ["the soup kitchen", "Disneyland", "the White House"];
let insertZ = [
  "spontaneously combusted",
  "melted into a puddle on the sidewalk",
  "turned into a slug and crawled away"
];

//3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION

randomize.addEventListener("click", result);

function result() {
  let itemX = randomValueFromArray(insertX);
  let itemY = randomValueFromArray(insertY);
  let itemZ = randomValueFromArray(insertZ);

  //replaces inserts in stortText w/ randomized strings from itemX,Y,Z
  let newStory = `It was 94 fahrenheit outside, so <span class="itemX">${itemX}</span> went for a walk. When they got to <span class="itemY">${itemY}</span>, they stared in horror for a few moments, then <span class="itemZ">${itemZ}</span>. Bob saw the whole thing, but was not surprised — <span class="itemX">${itemX}</span> weighs 300 pounds, and it was a hot day.`;

  //replaces 'Bob' w/ custom name if given
  if (customName.value !== "") {
    let name = customName.value;
    newStory = newStory.replace("Bob", name);
  }

  //converts fahrenheit to centigrade & pounds to stone
  if (document.getElementById("uk").checked) {
    let temperature = Math.round((94 - 32) * 5 / 9) + " centigrade";
    let weight = Math.round(300 * 0.071429) + " stone";
    newStory = newStory.replace("94 fahrenheit", temperature);
    newStory = newStory.replace("300 pounds", weight);
  }

  story.innerHTML = newStory;
  story.style.visibility = "visible";

  let spanX = story.getElementsByClassName("itemX");
  let spanY = story.getElementsByClassName("itemY");
  let spanZ = story.getElementsByClassName("itemZ");

  function setColor(arr, color) {
    for(let i=0; i<arr.length; i++) {
      arr[i].style.color = color;
    }
  }

  setColor(spanX,'red');
  setColor(spanY,'green');
  setColor(spanZ,'blue');
}
body {
  font-family: helvetica, sans-serif;
  width: 350px;
}

label {
  font-weight: bold;
}

div {
  padding-bottom: 20px;
}

input[type="text"] {
  padding: 5px;
  width: 150px;
}

p {
  background: #ffc125;
  color: #5e2612;
  padding: 10px;
  visibility: hidden;
}
<div>
  <label for="customname">Enter custom name:</label>
  <input id="customname" type="text" placeholder="">
</div>
<div>
  <label for="us">US</label><input id="us" type="radio" name="ukus" value="us" checked>
  <label for="uk">UK</label><input id="uk" type="radio" name="ukus" value="uk">
</div>
<div>
  <button class="randomize">Generate random story</button>
</div>
<!-- Thanks a lot to Willy Aguirre for his help with the code for this assessment -->
<p class="story"></p>

<script src="main.js"></script>
</>