簡體   English   中英

如何更改 CSS 中變量的顏色?

[英]How do I change the color of a variable in CSS?

只想computerScoreplayerScore中的數字改變顏色。 是否可以在 CSS 中做到這一點?

 function computerPlay(){ let values = ['Rock', 'Paper', 'Scissors'], valueToUse = values [Math.floor(Math.random()* values.length)]; return valueToUse; }; const rock = document.querySelector('#rock'); const paper = document.querySelector('#paper'); const scissors = document.querySelector('#scissors'); let computerSelection = document.querySelector('.computerSelection'); let result = document.querySelector('.result'); let score = document.querySelector('.computerScore', computerScore = 0, 'playerScore', playerScore = 0); rock.addEventListener('click', pickRock) function pickRock() { let comp = computerPlay()//the variable comp had to be created. Otherwirse, if I use computerPlay() in if statements, sometimes the text content would not appear. See stackoverflow comment. if (comp === 'Rock') { computerSelection.textContent = "Computer's Selection: Rock"; result.textContent = "It's a Tie!" score.textContent = `Computer Score: ${computerScore +=0} Your Score: ${playerScore +=0}` } else if (comp === 'Paper') { computerSelection.textContent = "Computer's Selection: Paper"; result.textContent = "Sorry! Paper beats Rock"; score.textContent = `Computer Score: ${computerScore +=1} Your Score: ${playerScore +=0}` } else if (comp === 'Scissors') { computerSelection.textContent = "Computer's Selection: Scissors"; result.textContent = "Great Job! Rock beats Scissors"; score.textContent = `Computer Score: ${computerScore +=0} Your Score: ${playerScore +=1}` } };
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My javascript</title> <link rel="stylesheet" href="javascript.css"> </head> <body> <main> <div class="wrapper"> <h1>Rock, Paper, Scissors!</h1> <h3>Instructions:</h3> <p>You will be playing against the computer. There will be a total of 3 rounds. Good luck!</p> <h2 id="choose">Choose:</h2> </div> <div class="container"> <button> <img id="rock" src="https://static.thenounproject.com/png/477914-200.png"> </button> </div> <div class="wrapper"> <p class='computerSelection'></p> <p class='result'></p> <p class='computerScore'></p> <p class='playerScore'></p> <p class='finalResult'></p> </main> <script src="javascript.js"></script> </html>

您可以設置元素的innerHTML並在應用CSS 的分數周圍添加span 標記。

例如:

score.innerHTML = `Computer Score: <span style="color:red;">${++computerScore}</span> Your Score: <span style="color:blue;">${playerScore}</span>`

您還可以使用類:

score.innerHTML = `Computer Score: <span class="computer-score">${++computerScore}</span> Your Score: <span class="player-score">${playerScore}</span>`

首先,您在結束</main>標記之前缺少結束</div> </main>標記。 在下面的示例中,錯誤/錯字已得到修復。

由於您是 JavaScript 的新手——可能還有 HTML 和 CSS——我將嘗試相對緩慢地分階段解決這個問題。 雖然您有一個“簡單的問題”需要解決,但我要做的第一件事是整理演示文稿,然后我將向您展示一種方法,您可以通過該方法減少您在頁面上更新的內容量.

我將要實施的演示更改主要是為了減少上下滾動,以便更輕松地可視化正在發生的事情和發生的變化。 為此,我們將使用 CSS Grid 和以下 CSS:

/* We use the universal selector ('*') to select all elements on
   the page, and also we select all of the ::before and ::after
   pseudo-elements; here we reset margin and padding to a known
   default (what the default is doesn't matter, just that you know
   what it is), and set all matching elements to the border-box
   means of box-sizing: */
*,
::before,
::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

main {
  /* We use CSS grid to layout the contents of the <main> element: */
  display: grid;
  /* We define a two-column layout, using the repeat() function, with
     each column taking one fractional unit of the available space: */
  grid-template-columns: repeat(2, 1fr);
  /* We define the width - using the CSS clamp() function as being
     50vw (fifty percent of the width of the viewport, with a
     minimum size of 200px and a maximum size of 600px: */
  width: clamp(200px, 50vw, 600px);
  /* A 1em top and bottom margin, with margin auto for left and right,
     this automatically centers the <main> element within its parent
     container: */
  margin: 1em auto;
  /* defining a gap between the grid-items (the child elements within
     an element set to display: grid); this also applies to elements 
     that are children of 'display: flex' elements: */
  gap: 0.5em;
}

.wrapper {
  /* places the element in the first column of the defined grid,
     and extending it to the last column of that defined grid: */
  grid-column: 1 / -1;
  text-align: center;
}

.container {
  /* anticipating at least two other elements to be added to this
     element ('scissors' and 'paper', unless you're playing 'rock,
     paper, scissors, lizard, Spock') so setting up the container
     to accept, and lay out, more elements automatically and
     predictably: */
  display: flex;
  /* allowing the flex-item elements to wrap into a new row (or
     column) if necessary: */
  flex-wrap: wrap;
  /* flex-items will be laid out spaced evenly with space between
     the elements and their parent-element's boundaries: */
  justify-content: space-around;
}

.container button {
  /* to show interactivity on hover: */
  cursor: pointer;
}

.results::before {
  /* using CSS generated content to display a header/title/hint
     as to what the element is for: */
  content: "Results: ";
  display: block;
  font-size: 1.2em;
  border-bottom: 2px solid #000;
}

 function computerPlay() { let values = ['Rock', 'Paper', 'Scissors'], valueToUse = values[Math.floor(Math.random() * values.length)]; return valueToUse; }; const rock = document.querySelector('#rock'); const paper = document.querySelector('#paper'); const scissors = document.querySelector('#scissors'); let computerSelection = document.querySelector('.computerSelection'); let result = document.querySelector('.result'); let score = document.querySelector('.computerScore', computerScore = 0, 'playerScore', playerScore = 0); rock.addEventListener('click', pickRock) function pickRock() { let comp = computerPlay() //the variable comp had to be created. Otherwirse, if I use computerPlay() in if statements, sometimes the text content would not appear. See stackoverflow comment. if (comp === 'Rock') { computerSelection.textContent = "Computer's Selection: Rock"; result.textContent = "It's a Tie!" score.textContent = `Computer Score: ${computerScore +=0} Your Score: ${playerScore +=0}` } else if (comp === 'Paper') { computerSelection.textContent = "Computer's Selection: Paper"; result.textContent = "Sorry! Paper beats Rock"; score.textContent = `Computer Score: ${computerScore +=1} Your Score: ${playerScore +=0}` } else if (comp === 'Scissors') { computerSelection.textContent = "Computer's Selection: Scissors"; result.textContent = "Great Job! Rock beats Scissors"; score.textContent = `Computer Score: ${computerScore +=0} Your Score: ${playerScore +=1}` } };
 *, ::before, ::after { margin: 0; padding: 0; box-sizing: border-box; } main { display: grid; grid-template-columns: repeat(2, 1fr); width: clamp(200px, 50vw, 600px); margin: 1em auto; gap: 0.5em; } .wrapper { grid-column: 1 / -1; text-align: center; background-color: #f903; } .container { display: flex; flex-wrap: wrap; justify-content: space-around; } .container button { cursor: pointer; } .results::before { content: "Results: "; display: block; font-size: 1.2em; border-bottom: 2px solid #000; }
 <main> <div class="wrapper"> <h1>Rock, Paper, Scissors!</h1> <h3>Instructions:</h3> <p>You will be playing against the computer. There will be a total of 3 rounds. Good luck!</p> <h2 id="choose">Choose:</h2> </div> <div class="container"> <button> <img id="rock" src="https://static.thenounproject.com/png/477914-200.png"> </button> </div> <!-- The following <div> was changed from div.wrapper to div.results, since while it remains a wrapping element, its role is different: it exists to present the results or outcome. Name your components appropriately and meaningfully, that way maintenance becomes easier because you know where to look and what each section is for --> <div class="results"> <p class='computerSelection'></p> <p class='result'></p> <p class='computerScore'></p> <p class='playerScore'></p> <p class='finalResult'></p> </div> </main>

JS小提琴演示

接下來,我們將整理 JavaScript 並更正代碼中似乎有錯誤的地方; 首先,所有不會改變的變量都將用const聲明(你的代碼中有一個特殊的constlet組合),我們將修復document.querySelector()的奇怪使用:

let score = document.querySelector('.computerScore', computerScore = 0, 'playerScore', playerScore = 0);

我可以直覺你的意圖,它應該在初始化相關變量時以某種方式同時選擇p.computerScorep.playerScore元素; 但是當變量被初始化時(很不符合我的預期) document.querySelector()將 &ndash 並且可以– 只返回一個element-node 或null 這種誤解的結果是,您只更新了p.computerScore元素的文本內容,而不是按照您的 HTML 建議使用這兩個元素。

所以,也就是說:修改后的 JavaScript:

// There was nothing wrong here, except that you initialised
// a variable purely in order to return it in the next line;
// this is a matter of preference and personal taste but I
// removed the variable instantiation and simply returned the
// result directly:
function computerPlay() {
  const values = ['Rock', 'Paper', 'Scissors'];
    return values[Math.floor(Math.random() * values.length)];
}

// You were using document.querySelector() so many times that,
// just to save your fingertips, it was worth defining a
// simple function (using Arrow syntax) to reduce the need to
// repeatedly type a longer method-call; here the function
// dQS() is defined as accepting an 'el' argument and will
// pass that argument to the inner document.querySelector()
// and simply returning the result:
const dQS = (el) => document.querySelector(el),

  // here all the document.querySelector() calls have been
  // changed, and still work perfectly:
  rock = dQS('#rock'),
  paper = dQS('#paper'),
  scissors = dQS('#scissors'),
  computerSelection = dQS('.computerSelection'),
  result = dQS('.result'),
  computerScoreElement = dQS('.computerScore'),
  // you were never getting, and therefore never using, this
  // element in your original code, I assumed - as the paragraph
  // above states - that you meant to, so I changed this around
  // in order that you could:
  playerScoreElement = dQS('.playerScore');

// all preceding variables are constants, but the scores will
// necessarily change therefore we declare with 'let' rather
// than const:
let computerScore = 0,
  playerScore = 0;

rock.addEventListener('click', pickRock)

function pickRock() {
  const comp = computerPlay();

  if (comp === 'Rock') {
    computerSelection.textContent = "Computer's Selection: Rock";
    result.textContent = "It's a Tie!"
    // here the score doesn't change, so there's no need
    // to adjust the score; therefore that's been removed.

  } else if (comp === 'Paper') {
    computerSelection.textContent = "Computer's Selection: Paper";
    result.textContent = "Sorry! Paper beats Rock";

    // here only the computerScore variable changes, so we
    // update only that score; we use the increment operator
    // as a prefix because we want to increment the variable
    // and then return it (computerScore++ would return the
    // variable unchanged, and then increment it):
    ++computerScore;

  } else if (comp === 'Scissors') {
    computerSelection.textContent = "Computer's Selection: Scissors";
    result.textContent = "Great Job! Rock beats Scissors";

    // as above:
    ++playerScore;
  }

  // here we update the scores in the elements:
  computerScoreElement.textContent = `Computer: ${computerScore}`;
  playerScoreElement.textContent = `Player: ${playerScore}`;
}

 function computerPlay() { const values = ['Rock', 'Paper', 'Scissors']; return values[Math.floor(Math.random() * values.length)]; } const dQS = (el) => document.querySelector(el), rock = dQS('#rock'), paper = dQS('#paper'), scissors = dQS('#scissors'), computerSelection = dQS('.computerSelection'), result = dQS('.result'), computerScoreElement = dQS('.computerScore'), playerScoreElement = dQS('.playerScore'); let computerScore = 0, playerScore = 0; rock.addEventListener('click', pickRock) function pickRock() { const comp = computerPlay(); if (comp === 'Rock') { computerSelection.textContent = "Computer's Selection: Rock"; result.textContent = "It's a Tie!" } else if (comp === 'Paper') { computerSelection.textContent = "Computer's Selection: Paper"; result.textContent = "Sorry! Paper beats Rock"; ++computerScore; } else if (comp === 'Scissors') { computerSelection.textContent = "Computer's Selection: Scissors"; result.textContent = "Great Job! Rock beats Scissors"; ++playerScore; } computerScoreElement.textContent = `Computer: ${computerScore}`; playerScoreElement.textContent = `Player: ${playerScore}`; }
 *, ::before, ::after { margin: 0; padding: 0; box-sizing: border-box; } main { display: grid; grid-template-columns: repeat(2, 1fr); width: clamp(200px, 50vw, 600px); margin: 1em auto; gap: 0.5em; } .wrapper { grid-column: 1 / -1; text-align: center; background-color: #f903; } .container { display: flex; flex-wrap: wrap; justify-content: space-around; } .container button { cursor: pointer; } .results::before { content: "Results: "; display: block; font-size: 1.2em; border-bottom: 2px solid #000; }
 <main> <div class="wrapper"> <h1>Rock, Paper, Scissors!</h1> <h3>Instructions:</h3> <p>You will be playing against the computer. There will be a total of 3 rounds. Good luck!</p> <h2 id="choose">Choose:</h2> </div> <div class="container"> <button> <img id="rock" src="https://static.thenounproject.com/png/477914-200.png"> </button> </div> <div class="results"> <p class='computerSelection'></p> <p class='result'></p> <p class='computerScore'></p> <p class='playerScore'></p> <p class='finalResult'></p> </div> </main>

所以現在,雖然我們稍微改進了您的 JavaScript,但我們仍然面臨您提出的問題:如何在不更改所有文本顏色的情況下輕松地為分數着色?

有兩種明顯的 – 明智的 – 方法(並且使用innerHTML並不是真正明智的,因為您在每次調用pickRock()函數時都在破壞和重新創建 DOM 的pickRock()

第一個選項是在 HTML 中使用嵌套元素,例如<span> ,第二個選項是使用 CSS 生成的內容(以兩種不同方式之一)。

因此,對於嵌套的<span> (其他元素可用),只需要進行三處更改:

  • 調整 JavaScript 中的選擇器,
  • 更新 CSS 以設置<span>元素的樣式,以及
  • 插入相關的 HTML。

 function computerPlay() { const values = ['Rock', 'Paper', 'Scissors']; return values[Math.floor(Math.random() * values.length)]; } const dQS = (el) => document.querySelector(el), rock = dQS('#rock'), paper = dQS('#paper'), scissors = dQS('#scissors'), computerSelection = dQS('.computerSelection'), result = dQS('.result'), // note the adjusted selectors below, selecting a // <span> which is the direct child of the '.computerScore' // element, and likewise with the '.playerScore': computerScoreElement = dQS('.computerScore > span'), playerScoreElement = dQS('.playerScore > span'); let computerScore = 0, playerScore = 0; rock.addEventListener('click', pickRock) function pickRock() { const comp = computerPlay(); if (comp === 'Rock') { computerSelection.textContent = "Computer's Selection: Rock"; result.textContent = "It's a Tie!" } else if (comp === 'Paper') { computerSelection.textContent = "Computer's Selection: Paper"; result.textContent = "Sorry! Paper beats Rock"; ++computerScore; } else if (comp === 'Scissors') { computerSelection.textContent = "Computer's Selection: Scissors"; result.textContent = "Great Job! Rock beats Scissors"; ++playerScore; } computerScoreElement.textContent = computerScore; playerScoreElement.textContent = playerScore; }
 *, ::before, ::after { margin: 0; padding: 0; box-sizing: border-box; } main { display: grid; grid-template-columns: repeat(2, 1fr); width: clamp(200px, 50vw, 600px); margin: 1em auto; gap: 0.5em; } .wrapper { grid-column: 1 / -1; text-align: center; background-color: #f903; } .container { display: flex; flex-wrap: wrap; justify-content: space-around; } .container button { cursor: pointer; } .results::before { content: "Results: "; display: block; font-size: 1.2em; border-bottom: 2px solid #000; } /* The CSS to style the relevant <span> elements, obviously they're both the same here but equally obviously they can be adjusted individually to your preference: */ .computerScore > span, .playerScore > span { color: darkblue; font-weight: 900; } /* Here we use generated content to insert a starting value of zero if - and only if - there is no content at all in the relevant element; no white-space, no descendants, no text; so as soon as there is any textContent inserted into the span it ceases to match the :empty selector and therefore the ::before element no longer shows: */ .computerScore > span:empty::before, .playerScore > span:empty::before { content: '0'; }
 <main> <div class="wrapper"> <h1>Rock, Paper, Scissors!</h1> <h3>Instructions:</h3> <p>You will be playing against the computer. There will be a total of 3 rounds. Good luck!</p> <h2 id="choose">Choose:</h2> </div> <div class="container"> <button> <img id="rock" src="https://static.thenounproject.com/png/477914-200.png"> </button> </div> <div class="results"> <p class='computerSelection'></p> <p class='result'></p> <!-- Note the inserted <span> elements below: --> <p class='computerScore'>Computer: <span></span></p> <p class='playerScore'>Player: <span></span></p> <p class='finalResult'></p> </div> </main>

JS小提琴演示

另一種方法是僅使用現有元素並使用 CSS 進行更改 - 並略微減少 JavaScript - 僅:

 function computerPlay() { const values = ['Rock', 'Paper', 'Scissors']; return values[Math.floor(Math.random() * values.length)]; } const dQS = (el) => document.querySelector(el), rock = dQS('#rock'), paper = dQS('#paper'), scissors = dQS('#scissors'), computerSelection = dQS('.computerSelection'), result = dQS('.result'), computerScoreElement = dQS('.computerScore'), playerScoreElement = dQS('.playerScore'); let computerScore = 0, playerScore = 0; rock.addEventListener('click', pickRock) function pickRock() { const comp = computerPlay(); if (comp === 'Rock') { computerSelection.textContent = "Computer's Selection: Rock"; result.textContent = "It's a Tie!" } else if (comp === 'Paper') { computerSelection.textContent = "Computer's Selection: Paper"; result.textContent = "Sorry! Paper beats Rock"; ++computerScore; } else if (comp === 'Scissors') { computerSelection.textContent = "Computer's Selection: Scissors"; result.textContent = "Great Job! Rock beats Scissors"; ++playerScore; } // here we've reduced the text we're inserting into the document to // just the variable: computerScoreElement.textContent = computerScore; playerScoreElement.textContent = playerScore; }
 *, ::before, ::after { margin: 0; padding: 0; box-sizing: border-box; } main { display: grid; grid-template-columns: repeat(2, 1fr); width: clamp(200px, 50vw, 600px); margin: 1em auto; gap: 0.5em; } .wrapper { grid-column: 1 / -1; text-align: center; background-color: #f903; } .container { display: flex; flex-wrap: wrap; justify-content: space-around; } .container button { cursor: pointer; } .results::before { content: "Results: "; display: block; font-size: 1.2em; border-bottom: 2px solid #000; } .computerScore, .playerScore { /* styles the color of all the content, but includes the score color: */ color: #000; } .computerScore::before { content: 'Computer score: '; /* styles the color of the CSS generated content, overriding the color defined above: */ color: orange; } .playerScore::before { content: 'Player score: '; /* styles the color of the CSS generated content, overriding the color defined above: */ color: red; }
 <main> <div class="wrapper"> <h1>Rock, Paper, Scissors!</h1> <h3>Instructions:</h3> <p>You will be playing against the computer. There will be a total of 3 rounds. Good luck!</p> <h2 id="choose">Choose:</h2> </div> <div class="container"> <button> <img id="rock" src="https://static.thenounproject.com/png/477914-200.png"> </button> </div> <div class="results"> <p class='computerSelection'></p> <p class='result'></p> <p class='computerScore'></p> <p class='playerScore'></p> <p class='finalResult'></p> </div> </main>

JS小提琴演示

此外,使用更多 CSS 生成的內容——加上一些 CSS 自定義屬性——我們還可以使用以下方法:

 function computerPlay() { const values = ['Rock', 'Paper', 'Scissors']; return values[Math.floor(Math.random() * values.length)]; } const dQS = (el) => document.querySelector(el), rock = dQS('#rock'), paper = dQS('#paper'), scissors = dQS('#scissors'), computerSelection = dQS('.computerSelection'), result = dQS('.result'), computerScoreElement = dQS('.computerScore'), playerScoreElement = dQS('.playerScore'); let computerScore = 0, playerScore = 0; rock.addEventListener('click', pickRock) function pickRock() { const comp = computerPlay(); if (comp === 'Rock') { computerSelection.textContent = "Computer's Selection: Rock"; result.textContent = "It's a Tie!" } else if (comp === 'Paper') { computerSelection.textContent = "Computer's Selection: Paper"; result.textContent = "Sorry! Paper beats Rock"; ++computerScore; } else if (comp === 'Scissors') { computerSelection.textContent = "Computer's Selection: Scissors"; result.textContent = "Great Job! Rock beats Scissors"; ++playerScore; } // here we use CSSStyleDeclaration.setProperty() to set a custom // CSS property and its value; we use a template-literal because // the value has to be quoted and a template-literal makes that // easier to do (this property will be read from CSS): computerScoreElement.style.setProperty('--currentComputerScore', `"${computerScore}"`); // here we update the HTMLOrForeignElement.dataset API to set // a property on the dataset Object of the element, and set its // value equal to the playerScore (this creates a custom data-* // attribute on the element, from which CSS can read the value // via the attr() function: playerScoreElement.dataset.current_player_score = playerScore; }
 *, ::before, ::after { margin: 0; padding: 0; box-sizing: border-box; } main { display: grid; grid-template-columns: repeat(2, 1fr); width: clamp(200px, 50vw, 600px); margin: 1em auto; gap: 0.5em; } .wrapper { grid-column: 1 / -1; text-align: center; background-color: #f903; } .container { display: flex; flex-wrap: wrap; justify-content: space-around; } .container button { cursor: pointer; } .results::before { content: "Results: "; display: block; font-size: 1.2em; border-bottom: 2px solid #000; } .computerScore, .playerScore { color: #000; } .computerScore::before { content: 'Computer score: '; color: orange; } /* here we use the --currentComputerScore custom property - defined in JavaScript - as the content for the ::after pseudo- element; the '0' following the name of the custom property is the fall-back value in the event the property doesn't resolve to a valid value, it's quoted because it needs to be a string rather than a CSS length or number: */ .computerScore::after { content: var(--currentComputerScore, '0'); color: darkblue; } .playerScore::before { content: 'Player score: '; color: red; } /* here we use the attr() function to retrieve the attribute-value of the 'data-current_player_score' defined by the JavaScript, and placed on the element; unfortunately while the documentation states that a default/fallback value might be supplied it's use is not currently usable in (my current version of) Chromium or Firefox, so I'm unable to verify if it might work: */ .playerScore::after { content: attr(data-current_player_score); color: limegreen; }
 <main> <div class="wrapper"> <h1>Rock, Paper, Scissors!</h1> <h3>Instructions:</h3> <p>You will be playing against the computer. There will be a total of 3 rounds. Good luck!</p> <h2 id="choose">Choose:</h2> </div> <div class="container"> <button> <img id="rock" src="https://static.thenounproject.com/png/477914-200.png"> </button> </div> <div class="results"> <p class='computerSelection'></p> <p class='result'></p> <p class='computerScore'></p> <p class='playerScore'><span></span></p> <p class='finalResult'></p> </div> </main>

JS小提琴演示

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM