我试图通过从页面上的图像标记(img #backSwitch)中拉出src属性来使jQuery动态更改背景图像(我将在稍后从php中的数组中随机拉出),并更改div .background-image元素的background-image属性值为src属性的值。我的console.log运行得很好,我想我在jQuery中所做的事情也很好,但很明显我做错了什么或者忽略了一个没有出现错误的错误。任何帮助都会很棒!
这是我的HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags always come first -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="background-image"></div>
<div class="content">
<img src="img/ped4.jpg" id="backSwitch" alt="Pedestal" />
</div>
<!-- jQuery first, then Bootstrap JS. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/js.js"></script>
</body>
</html>
这是我的jQuery
(function() {
var backSwitch = $('#backSwitch').attr('src'),
theURL = 'http://staging.youknowphabo.com/';
$('.background-image').css({backgroundImage: 'url('+theURL+backSwitch+');'});
console.log(theURL+backSwitch);
})();
这是我的CSS
@import url(//fonts.googleapis.com/css?family=Roboto+Slab:400);
.background-image {
position: fixed;
left: 0;
right: 0;
z-index: 1;
display: block;
background-image: url('http://666a658c624a3c03a6b2-25cda059d975d2f318c03e90bcf17c40.r92.cf1.rackcdn.com/unsplash_527bf56961712_1.JPG');
width: 100%;
height: 100%;
text-align: center;
margin: 0 auto;
background-size: cover;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
.content {
position: relative;
z-index: 999;
}
.content img {
width: 100%;
max-width: 600px;
padding: 30px;
display: block;
text-align: center;
margin: 0 auto;
}
答案 0 :(得分:1)
我认为问题是错字:
$('.background-image').css({backgroundImage: 'url('+theURL+backSwitch+')'});
尝试从CSS网址属性中删除分号。
您也可以这样写:
$('.background-image').css({'background-image': 'url('+theURL+backSwitch+')'});