[英]background-image style not working in HTML header
我試圖在按下按鈕時更改css類的“背景圖像:”。
jQuery的:
$(function() {
$('button').on('click', function() {
$('.masthead2').css('background-image', 'url("../img/whiteheader.png")');
});
});
CSS:
.masthead2 {
position: relative;
width: 100%;
height: auto;
min-height: 35rem;
padding: 15rem 0;
background-image: url("../img/roseheader.png");
background-position: center;
background-repeat: no-repeat;
background-attachment: scroll;
background-size: cover;
}
當我按下按鈕時,CSS樣式中的“背景圖像:”將被刪除。 然后,HTML隨之改變:
<header class="masthead2">
為此:
<header class="masthead2" style='background-image: url("../img/whiteheader.png");'
但是,在頁面上; 完全不顯示圖像。 我嘗試將網址直接復制到CSS中,並加載新圖像。 因此,我相信網址是正確的。
如果直接在CSS中更改背景圖片,則可以解決此問題。
圖像的路徑可能不正確。 如果它在css內,則該路徑是相對於css文件的,但在html內並不表示相同的位置。 嘗試圖像的絕對路徑。 例如
$(function() {
$('button').on('click', function() {
$('.masthead2').css('background-image', 'url("http://www.mywebsite.com/img/whiteheader.png")');
});
});
我已經檢查了完整的代碼,它可以在我的終端運行,請檢查您的圖片網址(如果其中存在圖片)。 這是代碼:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation</title>
<link rel="stylesheet" href="style.css" />
<style>
.masthead2 {
position: relative;
width: 100%;
height: auto;
min-height: 35rem;
padding: 15rem 0;
background-image: url("https://lh3.googleusercontent.com/proxy/ogwfaF0iwa05OnTNQFyD0rZ384sAN74p5xwJE6qfJmrEFcmgxlXo4zg22lrlaLcaS_hp9pFCu8s8QZ-GgDy37DxWVOHpq2B4IV35vb4wgHBWfJiYqI_AVARVMaguPane4Raedg=w530-h212-p-rw");
background-position: center;
background-repeat: no-repeat;
background-attachment: scroll;
background-size: cover;
}
</style>
</head>
<body>
<header class="masthead2"></header>
<button>Submit</button>
</body>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script>
$(function() {
$('button').on('click', function() {
$('.masthead2').css('background-image', 'url("https://upload.wikimedia.org/wikipedia/en/thumb/6/63/IMG_%28business%29.svg/1200px-IMG_%28business%29.svg.png")');
});
});
</script>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.