gpt4 book ai didi

javascript - 在 html 和 javascript 中设置文件 src 有什么区别

转载 作者:行者123 更新时间:2023-12-02 22:18:00 25 4
gpt4 key购买 nike

快速版本:

如果我制作一个 div,并在其中放入图像,它就可以正常工作。

this 
<img id="main_image"; src="~/images/tea_offer.jpg" style="width:100%; height:100%" />
gives
localhost/images/tea_offer.jpg

但后来我尝试用 javascript 更改图像

this
document.getElementById("main_image").src = "images/cake.jpg"
gives
localhost/home/~/images/cake.jpg

图像根本不起作用。我认为这====> localhost/home/~/images/cake.jpg。是错的。请帮忙。

长版。

我有一个简单的网站,它有一个背景图像和一个蓝色框。当您单击蓝色框时,背景图像会发生变化。图像本地存储在 wwwroot 中。单击蓝色框时,背景图像会变成白色,并且我的计算机无法找到它正在查找的图像。

proof the images are stored in propper place with propper name

如何让 javascript 像 html 一样查找图像?

最佳答案

在 JavaScript 版本中,不要在路径中添加“~”,而是使用“/”,使其成为“/images/cake.jpg”,从根目录进行查询。

更多信息:https://coderwall.com/p/8nhqeg/relative-paths-from-the-root-in-javascript

更新信息:

  • 您需要提供图像的绝对链接(这可能与 DEV 环境不同,可能是 localhost:80,与发布的 Prod 环境 http:....com/不同)。因此,最好将 BASE_URL 放在静态变量中,并将其添加到对图像的所有调用之前。

关于javascript - 在 html 和 javascript 中设置文件 src 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59322344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com