我刚刚想出了如何使用javascript更改图像的来源,现在即使我在Visual Studio中控制单击路径,它仍将元素设置为空白图像,好像找不到文件路径一样,我正确的形象。这是我更改图像源的代码:
setTimeout(function(){userImg.setAttribute('src', "file:///C:/Users/My%20Name/Desktop/websites/rockpaperscissors/images/paper.png")}, 300);
正在运行的代码段
setTimeout(function() {
userImg.setAttribute('src', "https://www.pinclipart.com/picdir/middle/327-3278638_note-clipart-blank-paper-png-download.png")
}, 300);
<title>
Rock Paper Scissors Game
</title>
<header>
<h1>Rock Paper Scissors</h1>
</header>
<div class="score-board">
<div id="user-label" class="badge">user</div>
<div id="computer-label" class="badge">comp</div>
<span id="user-score">0</span>:<span id="computer-score">0</span>
</div>
<div class="result">
<p>Make Your Move!</p>
</div>
<div class="choices">
<div class="choice" id="r">
<img src="images/rock.png" width="115" height="95">
</div>
<div class="choice" id="p">
<img src="images/paper.png" width="120" height="120">
</div>
<div class="choice" id="s">
<img src="images/scissors.png" width="130" height="110">
</div>
</div>
<div class="fighters">
<div class="fighter" id="u">
<img id="userimg" src="images/rock.png" width="370" height="300">
</div>
<div class="fighter" id="c">
<img id="compimg" src="images/rockflipped.png" width="370" height="300">
</div>
</div>
<div class="squares">
<div class="square" id="userSquare"></div>
<div class="square" id="computerSquare"></div>
</div>
<script src="app.js" charset="utf-8"></script>
答案 0 :(得分:0)
您不想使用 exact 文件路径,尤其是如果它最终要托管在服务器上时。您要做的就是从IIS,Apache,Nginx,Node.js,Xaamp,Wamp / Lamp / Mamp或其他一些Web服务器提供网站服务,以便您可以使用如下的 relative 路径:
setTimeout(function(){userImg.setAttribute('src', "/images/paper.png")}, 300);
在website.com
服务的地方,您可以使用保存它的文件夹中的目录以及/ images / js / css等子文件夹来获取资源。所以看起来像这样:
|_ website root folder
|_ index.html
|_ images
|_ yourimage.png
使用相对路径,您可以获得更好的安全性,这是一种标准做法。如果您托管网站,则使用确切的文件路径可以处理从本地文件系统到安全性问题的一系列问题。另外,您无法在计算机外部访问确切的路径,因此以后无论如何都必须对其进行更改。
答案 1 :(得分:0)
问题在于浏览器不会尝试获取该图像,而只是拿走了旧的图像。尝试替换整个图像元素。
function replaceImage (userImg) {
let target = userImg.parentElement // where to place new element
document.removeElement(userImg) // remove old element
let newImage = document.createElement('img') //create new element
newImage.setAttribute('src', 'C://filepath.jpg')
newImage.setAttribute('id', 'userimg')
target.appendChild(newImage) // place new element
}
函数appendChild()和createElement()应该警告浏览器它需要从新路径获取新图像。