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/

posted @ 2022-04-15 10:39  Micky233  阅读(2252)  评论(0编辑  收藏  举报