更改背景图片网址

时间:2018-01-04 20:07:12

标签: javascript css

我正在尝试更改div中的背景图像URL(见下文)。它在运行时在控制台中显示net::ERR_FILE_NOT_FOUND。新图像是否必须在本地托管?

<html>
  <head>
    <script>	
      function changeback() {
        var x = document.getElementById('im').value; 		 
        document.getElementById('containerH').style.backgroundImage = 'url(img/'+x+')';
      }		
    </script>
  </head>
  <body>
    <textarea id="im" onKeyUp="changeback();" onKeyPress="changeback();"></textarea>
    <br>
    <div id="containerH" style="background-image:url(https://thejasfiles.files.wordpress.com/2015/07/summerholidays-heading.jpg); width:200px; height:400px; margin-left: 12%; margin-top: -2%;">
    </div>
    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

这是因为'url(img/'+x+')';值。 img/是当前页面的相对路径,因此它会尝试在相对的“img”中查找本地图片。夹。

&#13;
&#13;
<html >
<head>
<script>	
function changeback() {
     var x = document.getElementById('im').value;	 
		         document.getElementById('containerH').style.backgroundImage = 'url(' + x + ')';
			    
		}	
		
</script>
</head>
<body>
<textarea id="im" onKeyUp="changeback();" onKeyPress="changeback();"></textarea><br>
<div  id="containerH" style="background-image:url(https://thejasfiles.files.wordpress.com/2015/07/summerholidays-heading.jpg); width:200px; height:400px; margin-left: 12%; margin-top: -2%;">
</div>
</div>
</body>
</html>
&#13;
&#13;
&#13;

请参阅另一篇关于the difference between relative and absolute paths的文章。

相关问题