您能否告诉我我必须在此处更改才能通过Javascript更改background-image
?
$(document).ready(function(){
$('p').css('background-image', 'url("misc/bilder/2.png")');
});
.p {
height: 100%;
width: 100%;
position: relative;
padding: 25%;
background-size: cover;
background-attachment: fixed;
-webkit-transition: all 0.2s ease;
-moz-transition: all 0.2s ease;
transition: all 0.2s ease;
background-image: url("misc/bilder/1.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Some text
</p>
谢谢!
答案 0 :(得分:1)
在您的CSS中,您引用.p这是一个类,但在您的javascript中,您引用的是p,这是一个元素。这可能会有所帮助:
$(document).ready(function(){
$('.p').css('background-image', 'url("misc/bilder/2.png")');
});
更新: 问题在我回答后更新了。除掉 。来自.p in css。像这样:
的CSS:
p {
//some css
}
的javascript:
$(document).ready(function(){
$('p').css('background-image', 'url("misc/bilder/2.png")');
});
HTML:
<p>
some text
</p>
答案 1 :(得分:1)
CSS选择器应该只是p
,除非class="p"
添加到段落<p>
。
.p
- 将选择段落(<p>
)with class="p"
。 .
是classname选择器。详细了解CSS Selector
$(document).ready(function() {
$('p').css('background-image', 'url("http://i.stack.imgur.com/vdlyZm.png")');
});
p {
height: 100%;
width: 100%;
position: relative;
padding: 25%;
background-size: cover;
background-attachment: fixed;
-webkit-transition: all 0.2s ease;
-moz-transition: all 0.2s ease;
transition: all 0.2s ease;
background-image: url("misc/bilder/1.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Some text
</p>
答案 2 :(得分:0)
您缺少类选择器,如下所示:
$('p').css('background-image', 'url("misc/bilder/2.png")');
//^--- missign . here..
当前您的选择器$('p')
选择页面中的所有段落。相反,它应该选择具有p
类的所有元素。
您的选择器应为$('.p')
,如下所示:
$('.p').css('background-image', 'url("misc/bilder/2.png")');
$(document).ready(function(){
$('.p').css('background-image', 'url("misc/bilder/2.png")');
});
.p {
height: 100%;
width: 100%;
position: relative;
padding: 25%;
background-size: cover;
background-attachment: fixed;
-webkit-transition: all 0.2s ease;
-moz-transition: all 0.2s ease;
transition: all 0.2s ease;
background-image: url("misc/bilder/1.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="p">Lorem ipsum</p>