<div> 使用 javascript 在 a 中播放图像



我试图在DIV中显示图像,如下JavaScript代码所示。"警报"告诉我我在功能中,但图像没有显示。如果可能的话,我想将图像大小缩小到页面尺寸。我知道我可以设置一个var,即" var swidth = screen.width;"。图像与代码相同的文件夹中。

请告诉我我在做什么错。

 <p align="left"><div id="myDiv">This is a div element.</div>
 <br>
 <button type="button" onclick="myFunction()">Set the background image of div</button>
 <script>
 function myFunction() {
 alert("inside myFunction");
 console.log();
 document.getElementById("myDiv").style.backgroundImage = "url('Nav-Aids-Logo-Long-Trans-1920.png')";
 }
 </script>

您需要将backgroundSize = "100% 100%"backgroundRepeat = "no-repeat"添加到"myDiv"元素样式,然后将backgroundImage更改为background。还要检查您要添加的图像的目录,如果是对或错的话。

它在此片段中起作用,除图像URL外,它与您的代码相同。因此,问题似乎是您的filepath或图像。

(顺便说一句:您的p标签在任何地方都没有关闭...(

function myFunction() {
 alert("inside myFunction");
 console.log();
 document.getElementById("myDiv").style.backgroundImage = "url('http://placehold.it/600x300/0fa')";
 }
 <p align="left"><div id="myDiv">This is a div element.</div>
 <br>
 <button type="button" onclick="myFunction()">Set the background image of div</button>

涉及您的愿望封面,其中有背景图像:在这种情况下,您必须将背景图像分配给body,而不是任何特定的Div:

function myFunction() {
 alert("inside myFunction");
 console.log();
 document.body.style.backgroundImage = "url('http://placehold.it/600x300/0fa')";
 }
<p align="left"><div id="myDiv">This is a div element.</div>
 <br>
 <button type="button" onclick="myFunction()">Set the background image of div</button>

最新更新