HTML、JS動態設置圖片img的src路徑


HTML、JS動態設置圖片img的src路徑

代碼可直接復制運行

通過請求獲取新的圖片url后賦值給img標簽

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>動態設置img的src路徑</title>

    <!-- 導入axios -->
    <script crossorigin="anonymous"
            integrity="sha512-bPh3uwgU5qEMipS/VOmRqynnMXGGSRv+72H/N260MQeXZIK4PG48401Bsby9Nq5P5fz7hy5UGNmC/W1Z51h2GQ=="
            src="https://lib.baomitu.com/axios/0.26.1/axios.min.js"></script>

    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>

    <!-- 引入樣式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入組件庫 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>

<body>


<img src="https://nd-static.bdstatic.com/m-static/disk-share/widget/pageModule/error-new/image/init-bg_1708266.png"
     style="width: 192px; height: 108px"
     id="myImg">


<div id="app">

    <div class="demo-image__preview">
        <el-image
                style="width: 100px; height: 100px"
                :src="url"
                :preview-src-list="srcList">
        </el-image>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
                srcList: [
                    'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
                    'https://staticedu-wps.cache.iciba.com/image/b85ef3f6ebc09ac6ccf2f8af7c03c991.png'
                ]
            }
        }
    })
</script>


<script>
    axios.get("https://api.oioweb.cn/api/picture/SogouServlet?keyword=%E7%8B%97")
        .then(function (response) {
            let imgUrl = response.data.result[0].imagelink
            console.log(imgUrl)

            setTimeout(function() {
              console.log("延遲執行的代碼");
              document.getElementById("myImg").src = imgUrl;
              document.getElementById("myImg").style = "width: 100px; height: 100px";
            }, 1000); // 1秒后執行

        })
        .catch(function (error) {
            console.error('加載異常');
            console.error(error);
        });

</script>

</body>

</html>

我的個人博客 https://blog.52ipc.top/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM