好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

原生js实现宽度计数器

本文实例为大家分享了js实现宽度计数器的具体代码,供大家参考,具体内容如下

一.用原生js实现宽度计数器

1.源码

<!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>计数器-原生js</title>
? ? <style>
? ? ? ? #box{
? ? ? ? ? ? width: 200px;
? ? ? ? ? ? height: 200px;
? ? ? ? ? ? border: 1px solid white;
? ? ? ? ? ? background-color: #878080;
? ? ? ? }
? ? ? ? /* 并集选择器 */
? ? ? ? button,span{
? ? ? ? ? ? margin: 10px 7px;
? ? ? ? }
? ? </style>
</head>
<body>
? ? <div id="box"></div>
? ? <button id="minus" onclick="minusWidth()">-</button>
? ? <button id="add" onclick="addWidth()">+</button>
? ? <button onclick="reset()">还原</button>
? ? <span id="result">200px</span>
</body>
</html>

<script>
? ? //修改数值
? ? var count=200;
? ? document.getElementById('add').addEventListener('click',()=>{
? ? ? ? if(count>500){
? ? ? ? ? ? alert("宽度超出限制");
? ? ? ? }
? ? ? ? else{
? ? ? ? ? ? count+=10;
? ? ? ? }
? ? ? ? document.getElementById('result').innerText = count+'px'; ?
? ? });
? ? document.getElementById('minus').addEventListener('click',()=>{
? ? ? ? if(count<10){
? ? ? ? ? ?alert("宽度超出限制");
? ? ? ? }
? ? ? ? else{
? ? ? ? ? ?count-=10;
? ? ? ? }
? ? ? ? document.getElementById('result').innerText = count+'px'; ?
? ? });
? ? //修改盒子宽度
? ? var boxWidth=200;
? ? var box=document.getElementById('box');
? ? function addWidth(){
? ? ? ?if(boxWidth>500){
? ? ? ? ? alert("图片宽度无法增加");
? ? ? ?}?
? ? ? ?else{
? ? ? ? ? boxWidth+=10;?
? ? ? ?}
? ? ? ?box.style.width=boxWidth+"px";
? ? };
? ? function minusWidth(){?
? ? ? ?if(boxWidth<10){
? ? ? ? ? alert("图片宽度无法减少");
? ? ? ?}
? ? ? ?else{
? ? ? ? ? boxWidth-=10;
? ? ? ?}
? ? ? ?box.style.width=boxWidth+'px';
? ? };
? ? function reset(){
? ? ? ?document.getElementById('box').style='200px';
? ? ? ?document.getElementById('result').innerHTML='200px';
? ? ? ?count=200;
? ? ? ?boxWidth=200;
? ? };
</script>

2.效果图

二.总结

addEventListener:用于监听事件并进行处理的函数。

innerText:用于获取文本内容的属性。(不包含html标签)

innerHTML:用于获取html标签内容的属性。(识别所有html标签)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

查看更多关于原生js实现宽度计数器的详细内容...

  阅读:31次