30.文字自动出现

文字自动出现

html部分

css部分

*{
    margin: 0;
    padding: 0;
}

body{
    background-color: darksalmon;
    height: 100vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

div{
    position: absolute;
    bottom: 20px;
    background-color: rgba(0, 0, 0, 0.1);
    padding: 10px 20px;
    font-size: 18px;
}
input{
    width: 50px;
    padding: 5px;
    font-size: 18px;
    background-color: darksalmon;
    border: none;
    text-align: center;
}
input:focus{
    outline: none;
}

js部分

// 获取dom
const text_box=document.getElementById('text');
const speed_box=document.getElementById('speed');


// 展示文本
const text="We Love Programming"


let end_index=1
let speed=300/speed_box.value
write()

// 写入内容
function write(){
    text_box.innerText=text.slice(0,end_index)
    end_index++
    if(end_index>text.length){
        end_index=1
    }
    setTimeout(write,speed)
}
// 监听速率变化
speed_box.addEventListener("input",(e)=>speed=300/speed_box.value)

效果

30.文字自动出现_第1张图片

你可能感兴趣的:(前端开发小案例,前端,javascript)