我第一次尝试用HTML/JS编码,我的目标是创建一个脚本,从列表中选择随机单词,我认为我在一条很好的道路上。我无法解决的问题是,我找不到改变脚本输出大小的方法,我只需要它大得多。
<html>
<button onclick="randomizeFunction()">NUOVA PAROLA</button>
<p>La parola è:</p>
<p id="randomWord"></p>
</html>
<script>
const myList = ["test1","test2","test3"];
randomizeFunction()
function randomizeFunction() {
document.getElementById("randomWord").innerHTML = myList[Math.floor(Math.random() * myList.length)]
}
</script>
我只能将字体设置为斜体
<html>
<button onclick="randomizeFunction()">NUOVA PAROLA</button>
<p>La parola è:</p>
<p id="randomWord"></p>
</html>
<script>
document.body.style.fontStyle = "italic"
const myList = ["test1","test2","test3"];
randomizeFunction()
function randomizeFunction() {
document.getElementById("randomWord").innerHTML = myList[Math.floor(Math.random() * myList.length)]
}
</script>
有人能帮忙吗?提前感谢,卢卡
您应该使用fontSize
CSS属性,并且必须将其设置为有效的字体大小,其中将包括单位(px
,em
,vh
,vw
,%
等)
<html>
<button onclick="randomizeFunction()">NUOVA PAROLA</button>
<p>La parola è:</p>
<p id="randomWord"></p>
<script>
const word = document.getElementById("randomWord");
const myList = ["test1","test2","test3"];
randomizeFunction()
function randomizeFunction() {
word.innerHTML = myList[Math.floor(Math.random() * myList.length)];
word.style.fontStyle = "italic"
word.style.fontSize = "4em"; //4x the size in effect at the moment
}
</script>
</html>
但实际上,因为你是新手,所以尽早养成好习惯是很重要的,你会发现人们在不知不觉中养成了很多坏习惯。
- 首先,你的HTML是无效的,因为你没有
head
或body
部分。 - 不要使用内联HTML事件属性,如
onclick
来设置事件处理程序。这是一个25年以上的技术,只是不会因为人们只是复制别人的代码而没有理解它。在JavaScript中单独使用.addEventListener()
- 不要使用
.innerHTML
,如果你可以避免它,因为有安全以及它对性能的影响。既然你没有设置或在字符串中获取任何HTML,只需使用.textContent
。 - 而不是用
.style
来设置元素的行内样式属性,应用或删除CSS类。这样你们最好分开HTML和CSS,更容易覆盖任何应用的CSS稍后,以及减少冗余代码的总数量,您将类型。 - 养成用分号结束语句的习惯。
script
元素必须是html
元素的一部分。通常是最好在body
元素结束之前包含它当它执行时,所有的HTML都已被解析到内存中。那么,这里是你的代码,调整:
<!DOCTYPE html>
<html>
<head>
<title>My Test Page</title>
<style>
/* Pre-define a CSS class to use when ready */
.bigItalic {
font-size:4em;
font-style:italic;
}
</style>
</head>
<body>
<button>NUOVA PAROLA</button>
<p>La parola è:</p>
<p id="randomWord"></p>
<script>
// Don't use HTML event attributes to set up event handlers,
// do it separately in the JavaScript
document.querySelector("button").addEventListener("click", randomize)
// Get references to the elements you'll use over and over, just once
const word = document.getElementById("randomWord");
const myList = ["test1","test2","test3"];
randomize();
function randomize() {
word.textContent = myList[Math.floor(Math.random() * myList.length)];
// Just apply the pre-made class instead of styling it here
word.classList.add("bigItalic");
}
</script>
</body>
</html>