[英]How do I change the background image position on a website using javascript?
[英]How do I change an image using javascript?
我希望我的代碼能夠更改圖像。
我已經確定腳本標簽是正確的。
var x = document.getElementById("card_1_img"); x.src = "images/1.png"; //the error occurs here
<img id="card_1_img" width="100" height="50">
錯誤:
未捕獲的類型錯誤:無法將屬性“src”設置為 null
您的腳本很可能在 HTML 加載之前運行。 嘗試將您的<script>
標簽放在頁面底部,在您關閉</body>
:
var x = document.getElementById("card_1_img"); x.src = "images/1.png";
<body> <img id="card_1_img" width="100" height="50"> <script src="script.js"></script> </body>
不知道是什么問題,我重現了它。
可能是您將 script 標簽放在 head 標簽中,而沒有創建 img 標簽。
var x = document.getElementById("card_1_img"); x.src = "https://hinhanhdephd.com/wp-content/uploads/2015/12/hinh-anh-dep-girl-xinh-hinh-nen-dep-gai-xinh.jpg";
<img id="card_1_img" width="100" height="50">
let chromeImg = "https://www.w3schools.com/images/compatible_chrome.gif"; let firefoxImg = "https://www.w3schools.com/images/compatible_firefox.gif"; function change(browser) { let img = document.getElementById("browser"); let name = document.getElementById("name"); if (browser.src.includes("chrome")) { img.src = firefoxImg; name.textContent = "FireFox"; } else { img.src = chromeImg; name.textContent = "Chrome"; } }
img, p { margin-left: 50px; }
<h5>Click on image below:</h5> <img id="browser" onclick="change(this)" src="https://www.w3schools.com/images/compatible_chrome.gif"> <p id="name"></p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.