【问题标题】:Changing color of words in sentence that match the words in an array更改句子中与数组中的单词匹配的单词的颜色
【发布时间】:2016-07-12 19:49:18
【问题描述】:

试图弄清楚如何编写代码 - 希望有人可以提供帮助!

我正在制作一个简单的项目,允许用户通过单击按钮来更改特定单词的颜色。

例如这是一句话:

<p>i cant believe mary tried to kill her own sister, bella ! </p>

而我想改变颜色的单词是“mary”、“kill”、“bella”

我知道我需要一个要更改的单词数组,但我不确定如何将句子与数组分配/连接。

我已经编写了一个按钮来改变整个句子的颜色*,但不知道如何连接数组元素 - 有人知道怎么做吗?谢谢!

*代码

 <p>i cant believe mary tried to kill her own sister, bella !</p> 
 <br/>

 <input id="changeColor" type="button" value="Change Color" />

//JQUERY CHANGES TEXT TO BLUE WHEN BUTTON IS CLICKED
$(function() {
    $('#changeColor').click( function() {
        $("p").css({"color":"blue"});
    });
});

编辑:查看了你们留下的 cmets - 很抱歉遗漏了重要信息!也感谢您的反馈!

【问题讨论】:

  • 你可以这样说。

    我不敢相信 mary 试图杀死她自己的妹妹 bella

  • 您能否编辑您的问题以包含您迄今为止尝试过的minimal, complete, and verifiable example?至于将单词链接到颜色,您可以考虑创建一个对象,其键是您要更改的单词,值是颜色。
  • 我已经编写了一个改变颜色的按钮 - 至少,你可以显示该代码

标签: javascript arrays colors


【解决方案1】:

const words = ['mary', 'kill', 'bella']

const p = document.querySelector('p')
var newHTML = p.innerHTML
words.forEach(word=>
  newHTML = newHTML.replace(word, `<span class="color">${word}</span>`)
)
p.innerHTML = newHTML
.color {
  color: red;
}
&lt;p&gt;i cant believe mary tried to kill her own sister, bella ! &lt;/p&gt;

首先,将要更改颜色的单词放入数组中。然后使用document.querySelector() 选择&lt;p&gt; 元素。将该元素的当前 HTML 内容分配给一个变量,并且对于数组中的每个单词,将该世界替换为 &lt;span&gt; 和一个包含该单词的类 color。然后将更改后的 HTML 分配给 &lt;p&gt; 元素的 innerHTML 属性。

您还必须在 CSS 中设置所需的颜色。

【讨论】:

  • 这正是我一直在寻找的 - 感谢您提供帮助并解决了这个乱七八糟的问题!
【解决方案2】:

如果您只是在制作一个“允许用户通过单击按钮更改特定单词颜色的简单项目”,那么您只需为每个单词添加 &lt;span&gt; 标记并更改它们即可在 javascript 中通过定位每个 id 如下所示。您说“我知道我需要一个数组”,但我不知道您的意思是像您认为您只能使用数组执行此操作,还是您想使用数组执行此操作。对我来说,这听起来像前者,所以下面没有使用数组和跨度标签。如果您需要对数组执行此操作,可以以非常相似的方式完成,但如果您想要 3 个单独的按钮,则没有必要。

function changeRed() {
 document.getElementById('red').style.color = 'red';
  }

function changeBlue() {
 document.getElementById('blue').style.color = 'blue';
  }

function changeGreen() {
 document.getElementById('green').style.color = 'green';
  }
 
<p>i cant believe <span id="red">mary</span> tried to <span id="blue">kill</span> her own sister, <span id="green">bella</span> ! </p>

<button type="button" onclick="changeRed()">mary</button>
<button type="button" onclick="changeBlue()">kill</button>
<button type="button" onclick="changeGreen()">bella</button>

【讨论】:

  • 嗨乔!请原谅我的问题含糊不清——我不确定如何表达我想问的问题。 (仍然没有)但我想用语言表达我试图改变句子和数组中的某些单词的颜色。 Gothdo 的回答有点澄清了我的目的,但你的回答很棒而且很有帮助。感谢您的反馈!
【解决方案3】:

你可以在单词周围加上span标签,然后给它一个id=maryid=kill等。

如果您希望所有这些单词都更改为相同的颜色,只需为每个 span 指定相同的类名即可。

你能附上你目前写的代码吗?

【讨论】:

    【解决方案4】:

    我在下面的代码cmets中解释了。

    HTML:

    <div id="sentenceContainer">Placeholder</div>
    <button id="changeButton">Change</button>
    <button id="resetButton">Reset</button>
    

    CSS:

    #sentenceContainer {
      position: relative;
      color: white;
      background-color: black;
      height: 40px;
      line-height: 40px;
    }
    
    #sentenceContainer > span:not(:first-child) {
      padding-left: 5px;
    }
    
    .red {
      color: red;
    }
    

    JavaScript:

    // We make an array of the words
    var words = ["i", "cant", "believe", "mary", "tried", "to", "kill", "her", "own", "sister,", "bella", "!"];
    
    // These are the indices from the array above that correspond to the words you want to turn red
    var redIndices = [3, 6, 10];
    
    $('#changeButton,#resetButton').on('click', writeWords);
    
    // This is the function that will write the sentence for us
    function writeWords(evt) {
    
      // Get the ID of the target to know if we are changing or resetting
      var red = evt && evt.target && $(evt.target).attr('id') === 'changeButton' ? true : false;
    
      // This grabs our sentenceContainer
      // Always grab these outside of any loops to speed up code execution
      // Otherwise there would be a DOM traversal for each iteration of the loop
      var sentenceContainer = $('#sentenceContainer');
    
      // Empty it so it doesn't repeat the sentence
      sentenceContainer.empty();
    
      // Iterate the words array
      for (var i = 0; i < words.length; i++) {
    
        // Generate the container
        var wordSpan = $('<span></span>');
    
        // Add the word to it
        wordSpan.text(words[i]);
    
        // If this is a word we want red, from redIndices - we add the class red
        if (red && redIndices.indexOf(i) >= 0)
          wordSpan.addClass('red');
    
        // Append the word container to the sentence container
        sentenceContainer.append(wordSpan);
      }
    
    };
    
    writeWords();
    

    现场观看:

    http://codepen.io/noahtkeller/pen/QEOOyL

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 2015-09-05
      • 2018-09-18
      相关资源
      最近更新 更多