【问题标题】:How to change the background color of webpage randomly using a json api?如何使用json api随机更改网页的背景颜色?
【发布时间】:2019-07-21 02:09:37
【问题描述】:

我想根据这个给出随机颜色的 json 文件执行 javascript onload 来随机更改网页的背景颜色。

http://api.creativehandles.com/getRandomColor

【问题讨论】:

    标签: javascript html json


    【解决方案1】:
    // this function will be triggered when the page loads. Every time you refresh the page a new background color will be set because this function will be invoked 
    window.addEventListener('load', function() {
       // fetch is in charge of getting the data from the API
       fetch('http://api.creativehandles.com/getRandomColor') // Call the fetch function passing the url of the API as a parameter
    .then(function(response) {
    
                 response.json().then(function(data){
                     let color = data["color"]; 
                    document.body.style.backgroundColor = color;
                 })
    
             })
    .catch(function() {
        // This is where you run code if the server returns any errors
    });
    })
    

    您还可以将所有获取逻辑提取到一个单独的函数中并创建一个按钮,该按钮在单击时调用该函数,从而在每次单击按钮时更改背景颜色

    【讨论】:

    • 你测试了吗?但是,这对我不起作用
    • 我刚刚更新了答案并进行了测试。有效,现在试试。如果您对我的 cmets 未涵盖的代码有任何其他问题,请告诉我。抱歉之前没用,我用手机写了答案,无法测试
    猜你喜欢
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多