一、创建button按钮
1 HTML结构
<div class="action"><button data-speed="slow">慢速</button> <!-- 自定义属性 --><button data-speed="normal" class="active">中速</button><button data-speed="fast">快速</button>
</div>
2 设置按钮的一般样式
.actions{position: absolute;top: 0;right: 0;/* border: 1px solid red; */display: flex;flex-direction: column;
}.actions>button{margin: 10px;padding: 8px 10px;background: #ddd;border: none; /*去除默认按钮的 边框样式*/
}
3 设置被选中按钮的样式
.actions>button.active{box-shadow: 1px 1px 1px rgba(0,0,0,0.8); /* box-shadow样式*/
}/* .actions>button:focus{outline: none;} 去除默认按钮的 选中边框颜色
*/
二、引入jquery
1 安装初始化yarn,用yarn引入jquery依赖
?yarn官网
2 创建.gitignore文件来忽略 node_mldules
?用git status -sb 命令行 查看是否忽略成功
3 强制引入node_mldules里的 单个jquery文件
?用 git add -f node_modules/jquery/dist/jquery.min.js 命令行 强制添加
4 在index.html里 引入jquery
三、用jquery监听绑定按钮并设置速度
1 设置动态改变active的所属
$('.actions').on('click', 'button', function(e){let $button = $(e.currentTarget) //当前指向元素buttonlet speed = $button.attr('data-speed') //获取其属性值console.log(speed)$button.addClass('active') //增加类.siblings('.active').removeClass('active') //去除兄弟元素类
......
})
2 实现点击变速按钮后,真的也改变展示速度
因为setInterval只会读取一次 延迟时间的值,所以不能实现改变展示速度;
这时候,我们可以用 SetTimeOut()来实现(通过递归)
var duration = 20function writeCode(prefix,code,fn){let container = document.querySelector('#code')let styleTag = document.querySelector('#styleTag')let n = 0// let id = setInterval(() => {setTimeout(function run(){n+=1;container.innerHTML = code.substring(0,n)styleTag.innerHTML = code.substring(0,n)container.scrollTop = container.scrollHeightif(n < code.length){setTimeout(run, duration) //再次递归调用setTimeout}else{fn && fn.call()}}, duration)}
3 通过点击按钮,就改变 duration的值,就可以实现展示速度变化
$('.actions').on('click', 'button', function(e){let $button = $(e.currentTarget) // buttonlet speed = $button.attr('data-speed')console.log(speed)$button.addClass('active').siblings('.active').removeClass('active')switch (speed){case 'slow':duration = 100breakcase 'normal':duration = 50breakcase 'fast':duration = 10break}})function writeCode(prefix,code,fn){let container = document.querySelector('#code')let styleTag = document.querySelector('#styleTag')let n = 0// let id = setInterval(() => {setTimeout(function run(){n+=1;container.innerHTML = code.substring(0,n)styleTag.innerHTML = code.substring(0,n)container.scrollTop = container.scrollHeightif(n < code.length){setTimeout(run, duration)}else{fn && fn.call()}}, duration)}
四 Reference
??1 data开头的属性;
??2 box-shadow介绍;
??3 yarn官网;
??4 jQuery 中文文档;