[英]How to update the background-image size dynamically in Javascript
我是编程新手,目前正在尝试我的第一个迷你项目——一个单词定义游戏。
我在输入字段上有一个事件侦听器,每次达到某个分数时都会更改背景图像。 我的问题是,每次更改背景图像时,都会丢失 CSS 样式属性,即backgroundSize = cover;
.
我做了一个 function 将backgroundSize
值更改为cover
,这只有在我在控制台中调用它时才有效。 我也试过内联 styles,没有效果。
我只是无法让它通过 javascript 文件(既不是eventListener
也不是 if 语句)工作。
加载的图像始终设置为auto
,我需要将其设置为“封面”。
任何帮助将不胜感激。
body {
background: url("/IMG/moebius.jpg");
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
let changeBackground = () => {
document.body.style.backgroundSize = "cover";
return document.body.style.backgroundSize;
}
defInputField.addEventListener("keyup", () => {
// document.body.style.backgroundSize = "cover";
setTimeout(userScore, scoreInterval);
if (splitInputWords.length < 2) {
correct.style.display = "none";
incorrect.style.display = "none";
displayScore.style.display = "none";
};
if (totalScore > 5) {
document.body.style.background = "url('/IMG/moebius3.jpg')";
};
if (totalScore > 10) {
document.body.style.background = "url('/IMG/moebius.jpg')";
};
if (userScore() >= 3 || userScore() >= splitDisplayedDef().length) {
correct.style.display = "block";
incorrect.style.display = "none"
displayScore.textContent = userScore();
displayScore.style.display = "block";
} else {
incorrect.style.display = "none";
correct.style.display = "none";
displayScore.display ="none";
};
});
defInputField.addEventListener("keydown", (e) => {
if (e.keyCode === 13 && userScore() >= 1) {
totalScore += userScore();
totalScore--;
currentLevel++;
newDefButton.textContent = "Definition"
let newWordObject = newWordObjectGenerator();
displayNewDef.style.display = "none";
correct.style.display = "none";
incorrect.style.display = "none";
displayScore.style.display = "none";
defInputField.value = "";
displayNewWord.textContent = newWordObject.word;
displayNewDef.textContent = newWordObject.definition;
scoreTracker.textContent = "Total Score = " + " " + totalScore;
levelTracker.textContent = "Level = " + " " + currentLevel;
console.log(currentLevel);
console.log(totalScore);
}});
当您调用图像路径时,使用backgroundImage
而不是background
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.