是否可以更改 ap 中特定值的样式?

我有一个带有文本的 ap,该文本在单击按钮时会发生变化,每个按钮根据 var 的值显示不同的文本,我希望其中一个文本具有不同的字体大小。


var language = " "; /* this var changes when another function fires, don't mind this, just know that the var changes and the possible values are 1,2,3 */


function changeText(text1, text2, text3) {

  if (language == 1) {

    document.getElementById('text').innerHTML = text1;

  } else if (language == 2) {

    document.getElementById('text').innerHTML = text2;

  } else if (language == 3) {

    document.getElementById('text').innerHTML = text3;

  } else {

    document.getElementById('text').innerHTML = "Don't think about this";

  }

}

/*yeah, I should be more DRY and not repeat document.getElementById('text') all over*/


button.addEventListener('click', () => changeText('whales', 'snails', 'this is the specific text that needs a different font-size'));

button2.addEventListener('click', () => changeText('bees', 'trees', 'this text3 is ok with the actual font-size'));

#text {

  font-size: 14px;

}

<p id='text'> dinamic text is in here </p>

我希望特定的 text3 具有不同的字体大小,而不是所有的 text3。我修改了函数changeText,所以当language == 3 时#text 的字体大小不同,但这当然适用于所有text3。希望我很清楚,感谢您的帮助。


我检查了类似的问题,但如果我这样做:


else if (language == 3) {

 document.getElementById('text').innerHTML = text3;

 document.getElementById('text').style.fontSize = 10px;

它改变了所有 text3 的字体大小。


慕尼黑8549860
浏览 122回答 2
2回答

胡子哥哥

由于您正在更改innerHTML(与innerText 相对),您可以在文本中添加html 标签。例如:JSbutton.addEventListener('click', () => changeText('whales', 'snails', '<small>this is the specific text that needs a different font-size</small>'));button2.addEventListener('click', () => changeText('bees', 'trees', 'this text3 is ok with the actual font-size'));CSS#text>small {&nbsp; font-size: 10px;}由于您在单击不同的按钮时调用相同的函数,因此它们将具有相同的行为。因此,如果您想以编程方式执行此操作,您将需要添加一个新函数或使用奇怪的逻辑使已经庞大的函数变得过于复杂。弹出的真正问题是:你为什么想要这种行为?

幕布斯6054654

&nbsp; var text = document.getElementById('text');&nbsp; &nbsp; function changeText(text1, text2, text3, button) {&nbsp; &nbsp; &nbsp; // default behaviour&nbsp; &nbsp; &nbsp; text.style.color = "red";&nbsp; &nbsp; &nbsp; if (language == 1) text.innerHTML = text1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else if (language == 2) text.innerHTML = text2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else if (language == 3){&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text.innerHTML = text3;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // different behaviour&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(button == "button1")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text.style.color = "green";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; else text.innerHTML = "Don't think about this";&nbsp; &nbsp; }<button onclick="changeText('hello','banana','wow','button1');" id="button1"><button onclick="changeText('vewewve','vdsvs','dgsag','button2');" id="button2">每次单击按钮时,此代码都会默认设置您的文本,并且语言不是 3。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript