用jquery改变div背景不工作

时间:2016-07-01 11:05:34

标签: jquery css cordova

我有一个div,我想改变背景图像。在我的代码上,如果参数被更改,它将在页面加载时更改。我在这个jsfiddle上写了一个示例代码:

https://jsfiddle.net/08ovv0r4/

正如您所看到的,当我按下按钮时,div背景会改变,但在我的代码中,背景图像不会加载,只需更改为白色背景。 我的代码上的div的css:

div[data-role="page"]{ 
min-height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
border: 0px;
background-image:url('../img/blue_background.jpg');
}

我改变背景的代码行:

$('div[data-role="page"]').css('background-image','url("../img/green.jpg")');

新图片位于我的www文件中的img文件中。在css上加载初始图像的代码没有问题,但是当我更改它时,不会加载。已经在stackoverflow上尝试了一些问题的许多答案,但没有一个解决。 有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

代码完全没问题。 请注意 每当您尝试使用jQuery添加CSS时,CSS代码都会直接添加到页面上的元素中。因此,在这种情况下,每当您尝试使用jQuery在HTML中添加任何基于CSS的URL时,都应该使用考虑HTML(或View)文件的路径。 以上显示CSS文件中图像路径的示例是

background-image:url('../img/<AN IMAGE FILE>');

与jQuery中的路径相同

$('div[data-role="page"]').css('background-image','url("../img/<AN IMAGE FILE>")');

这就是你错了。请考虑HTML文件,在jQuery代码中更正图像路径。

答案 1 :(得分:0)

可能是文件层次结构问题。

您会看到,通过链接标记加载样式文件时,将使用样式文件的目录解析相对URL。

html / script标签也一样。

.
|   index.html
+---css
|       style.css // Just the css, you already presented above.
\---img
    blue_background.jpg
    green_background.jpg

// index.html
<html>
<head>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
    <div data-role="page">Test</div>
    <script>
        function fWrong() {
            var div = document.querySelector('div[data-role="page"]');
            // "../img" does not point to the intended img directory.
            // Because index.html and img direcotry at the same level.
            div.style.backgroundImage = "url('../img/green_background.jpg')";
            setTimeout(fRight, 2000);
        }
        function fRight() {
            var div = document.querySelector('div[data-role="page"]');
            // Just one dot less. "./img" does point to the intended img directory.
            div.style.backgroundImage = "url('./img/green_background.jpg')";
        }
        setTimeout(fWrong, 2000);
    </script>
</body>
</html>