javascript - 使用 JavaScript 更改背景重复图像

标签 javascript image background repeat

我正在尝试创建一个脚本,用于在鼠标悬停事件中更改元素的重复背景图像。不幸的是它不能正常工作。我已经找到了几种使用 JavaScript 执行此操作的可能方法,但没有一种方法对我有用。我该如何解决这个问题?

以下代码无法正常工作:

    while (document.getElementById("content_" + modid + "_" + i) != null) {
        document.getElementById("content_" + modid + "_" + i).style.display = "none";
        document.getElementById("menu_" + modid + "_" + i).style.backgroundImage = "url(psycho_normal.jpg)";
        document.getElementById("menu_" + modid + "_" + i).style.backgroundPosition = "top left";
        document.getElementById("menu_" + modid + "_" + i).style.backgroundRepeat = "repeat-x";
        i++;
    }
    document.getElementById("menu_" + modid + "_" + ind).style.backgroundImage = "url(phycho_hover.jpg)";
    document.getElementById("menu_" + modid + "_" + ind).style.backgroundPosition = "top left";
    document.getElementById("menu_" + modid + "_" + ind).style.backgroundRepeat = "repeat-x";

但是如果我尝试使用 backgroundColor 属性,它工作正常:

    while (document.getElementById("content_" + modid + "_" + i) != null) {
        document.getElementById("content_" + modid + "_" + i).style.display = "none";
        document.getElementById("menu_" + modid + "_" + i).style.backgroundColor = "#000000";
        i++;
    }
    document.getElementById("menu_" + modid + "_" + ind).style.backgroundColor = "#ff0000";

最佳答案

编写一个 CSS 类并像这样在 JavaScript 中调用它

document.getElementById("menu_" + modid + "_" + i).className = "yourcssclass"

看看会发生什么。

关于javascript - 使用 JavaScript 更改背景重复图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1906741/

相关文章:

image - 如何在 flutter web 程序中压缩图像

java - 我应该使用哪个 API 从图像中提取信息?

android - 如何更新服务类中更新的textview文本

iphone - UIApplicationDidEnterBackgroundNotification 被多次调用

iphone - 使用后台任务的 Voip 应用程序

javascript - Nashorn loadWithNewGlobal 功能细节

javascript - 如何避免困惑的嵌套 if-else 或 switch

php - 通过PHP/MySQL上传图片

javascript - Vuex 计算属性不更新 v-show

javascript - 重新索引数组