我想改變我的標題的背景圖片,我正在使用的JavaScript代碼工作得很好,但是當我重新加載頁面時,圖像被重置爲默認值。 我想要background-image屬性來獲取我從輸入分配的新值。如何更改標題的背景圖像?
下面的代碼
HTML -
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel=stylesheet href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.css">
<title>CorpoViz Admin</title>
<script src="JS/editor.js"></script>
</head>
<body onload=iFrameOn()>
<div class="jumbotron" id=headerBg>
<div class="container-fluid">
<h1>Heading</h1>
<span style="float:right;">
<input type='file' id='getval' class="inputfile btn btn-default" />
<label for="getval" class="btn btn-default" style="font-size:20px;">Choose an image</label>
</span>
的JavaScript -
document.getElementById('getval').addEventListener('change', readURL, true);
function readURL(){
var file = document.getElementById("getval").files[0];
var reader = new FileReader();
reader.onloadend = function(){
document.getElementById('headerBg').style.backgroundImage = "url(" + reader.result + ")";
}
if(file){
reader.readAsDataURL(file);
document.getElementById('headerBg').style.backgroundImage = <?php echo "\"url(\" + reader.result + \")\"; " ?>
}
document.getElementById('headerBg').style.backgroundImage = "url(" + reader.result + ")";
}
CSS -
#headerBg{
background-image:url('');
background-size:cover;
background-position: center;
}
你在文件更改調用readUrl所以當你重新加載你的頁面需要更改文件以更改背景 – Araz
您期望得到什麼結果? –
即使在我重新加載頁面後,我也希望保留背景圖片@ TarasKumpanenko –