![](/img/trans.png)
[英]Dynamically edit img src based on device orientation with JS or JQuery
[英]How to edit src of <figure> dynamically in js
我正在嘗試在<figure>
HTML 標記內編輯 img 的 src 屬性,但很驚訝地知道 src 不是圖中的屬性(可能是錯誤的)。
<figure data-asset-id="dfdsf"><img src="https:/assets/conference-gffe9859b2_640.jpg" data-asset-id="dfdsf" data-image-id="dfdsf" alt="conference pic"></figure>
它返回的圖上有document.getAttribute
<img src="https://assets/conference-gffe9859b2_640.jpg" data-asset-id="dfdsf" data-image-id="dfdsf" alt="conference pic">
作為一個字符串,所以想過使用 DOM Parser 將它轉換成 HTML,但對我來說沒有成功。
任何線索我可能會丟失什么?
對於那些不了解 HTML <figure>
元素的人。 標准的<figure>
元素如下所示
<figure>
<img src="pic_trulli.jpg" alt="Trulli" style="width:100%">
<figcaption>Fig.1 - Trulli, Puglia, Italy.</figcaption>
</figure>
如果有人正在尋找答案
const figureEle = document.querySelector("[data-asset-id='dfdsf']")
const ChildImg = figureEle.childNodes[0]
ChildImg.setAttribute('src',newURL)
不確定它是否是最好的,但它可以完成工作。
<img id="uniqueId" src="https:/assets/conference-gffe9859b2_640.jpg" data-asset-id="dfdsf" data-image-id="dfdsf" alt="conference pic">
在 JS 中,加載后或在任何事件/函數上
getElementById('uniqueId').src = 'newURL'
或按按鈕
<button onclick="document.getElementById('uniqueId').src='newURL'">Turn off the light</button>
您的<figure>
元素似乎沒有 src 屬性,但<img>
元素有。 在任何一種情況下,首先選擇元素,然后獲取/設置屬性。 .src
有一個快捷方式。
document.querySelector("img").src;
document.querySelector("figure").setAttribute("name", "helloButton");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.