HTML+CSS+JS实现简易汇率计算器(使用Fetch)

还是github上找的小玩意跟着模仿着敲的。
首先看一下fetch,我也是学过ajax之后头一次见这玩意,然后就看着人家代码顺便上MDN看了一下。

Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应。它还提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。
反正这个东西好像就是比ajax要牛的东西?具体的还是MDN看一下文档吧

MDN-fetch链接

直接看最基本用法:

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

可以log看一下返回的东西就差不多知道咋用了吧

看一下汇率计算器
HTML+CSS+JS实现简易汇率计算器(使用Fetch)_第1张图片
直接上源码

html代码


    "img/money.png" alt="">
    

Exchange Rate Calculator

"description">Choose the currency and the amounts to get the exchange rate

"container">
"top flex"> "number" value="1" placeholder="0" id="input-tb">
"medium flex">

"rate">

"bottom flex"> "number" placeholder="0" id="input-db">

css代码

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

select:focus,
input:focus,
button:focus {
    outline: 0;
}

body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #f4f4f4;
}

img {
    width: 150px;
}

h1 {
    margin: 22px 0;
    color: rgb(47, 186, 158);
}

.description {
    margin: 16px 0;
}

select {
    padding: 9px 5px 9px 9px;
    font-size: 16px;
    background: transparent;
    border: 1px #dedede solid;
    border-radius: 5px;
}

input {
    font-size: 30px;
    text-align: right;
    border: 0;
    background: transparent;
}

.flex {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.top {
    padding: 40px 0;
}

.swapBtn {
    padding: 5px 12px;
    background-color: rgb(47, 186, 158);
    color: #fff;
    border-radius: 5px;
}

.rate {
    color: rgb(47, 186, 158);
    font-size: 14px;
    padding: 0 10px;
}

.bottom {
    padding: 40px 0;
}

js代码

var selectTb = document.querySelector('#choose-tb')
var selectDb = document.querySelector('#choose-db')
var inputTb = document.querySelector('#input-tb')
var inputDb = document.querySelector('#input-db')
var swapBtn = document.querySelector('.swapBtn')
var rateData = document.querySelector('.rate')

function calculate() {
    fetch('https://open.exchangerate-api.com/v6/latest')
        .then(res => res.json())
        .then(data => {
            rate = data.rates[selectDb.value] / data.rates[selectTb.value]
            rateData.innerText = `1${selectTb.value}=${rate} * ${selectDb.value}`
            inputDb.value = (inputTb.value * rate).toFixed(2)
        })
}
selectTb.addEventListener('change', calculate)
selectDb.addEventListener('change', calculate)
inputTb.addEventListener('input', calculate)
inputDb.addEventListener('input', calculate)

swapBtn.addEventListener('click', () => {
    var temp = selectDb.value
    selectDb.value = selectTb.value
    selectTb.value = temp
    calculate()
})

calculate()

API用的是人家原来项目上的,所以这个汇率八成不太符合实际吧。

你可能感兴趣的:(html,css,javascript)