如何在Javascript中动态更新背景图像大小
我是编程新手,目前正在试验我的第一个迷你项目——一个单词定义游戏 我在输入字段上有一个事件监听器,每次达到某个分数时,它都会更改背景图像。我的问题是,每次更改背景图像时,它都会丢失其CSS样式属性,即backgroundSize=cover 我做了一个函数来更改backgroundSize的值,使其覆盖,这只有在控制台中调用它时才有效。我也尝试过内联样式,但没有效果 我只是无法通过javascript文件eventListener或if语句使其工作 加载的图像总是设置为自动,我需要这是封面 任何帮助都将不胜感激如何在Javascript中动态更新背景图像大小,javascript,html,css,Javascript,Html,Css,我是编程新手,目前正在试验我的第一个迷你项目——一个单词定义游戏 我在输入字段上有一个事件监听器,每次达到某个分数时,它都会更改背景图像。我的问题是,每次更改背景图像时,它都会丢失其CSS样式属性,即backgroundSize=cover 我做了一个函数来更改backgroundSize的值,使其覆盖,这只有在控制台中调用它时才有效。我也尝试过内联样式,但没有效果 我只是无法通过javascript文件eventListener或if语句使其工作 加载的图像总是设置为自动,我需要这是封面 任何
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。请在您的问题中包含相关代码。能否将您的代码简化为如何实现此功能的最小示例?请尝试css set background size:cover!重要的我已经包括了一些主要的代码,但是里面乱七八糟的,我还没有对所有这些东西有足够的把握来有效地最小化。我计划“重新格式化”,我只想先解决这个问题。style.background是一个用于许多不同的background-*属性的函数。这意味着当您使用style.background时,您将覆盖所有其他属性,包括backgroundSize。改用style.backgroundImage。非常感谢您的回答,您可能为我节省了20多个小时的无谓调试。没有注意到那里的灰色勾号,接受。没有投票权,因为这是我的第一篇文章。