首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Javascript中动态更新背景图像大小

如何在Javascript中动态更新背景图像大小
EN

Stack Overflow用户
提问于 2019-10-30 17:40:00
回答 1查看 70关注 0票数 0

我是编程新手,目前正在试验我的第一个迷你项目--一个单词定义游戏。

我在一个输入字段上有一个事件侦听器,它会在每次达到某个分数时更改背景图像。我的问题是,每次更改背景图像时,它都会丢失它的CSS样式属性,即backgroundSize = cover;

我创建了一个函数,将backgroundSize值更改为cover,只有在控制台中调用它时才有效。我也尝试过内联样式,但没有效果。

我只是不能通过javascript文件(既不是eventListener也不是if语句)让它工作。

加载的图像总是设置为auto,我需要这个是“封面”。

任何帮助都将不胜感激。

代码语言:javascript
运行
复制
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);

}});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-30 19:04:31

调用镜像路径时,请使用backgroundImage而不是background

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58622425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档